• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
reLeetCode 热题 100- 239. 滑动窗口最大值 队列

 

 

image

 队列记录最大值集合

方法一1 枚举 速度嘛 n*k

 

方法2 map 记录频次 通过速度慢

 

方法3 队列记录当前最大值 最快

 

image

 

image

 

image

 

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
         
        vector<int> result; 
        if(nums.size()==0 || k==0){
            return result;    
        }

      
        deque<int> result_index; 
        // 4 3 1      4 2 3-> 4 2-> 4 3
        for(int i=0;i<k;i++){
            
            while(!result_index.empty() && nums[i]>nums[result_index.back()]){
                result_index.pop_back();
            }
            result_index.push_back(i);
        }

        result.push_back(nums[result_index.front()]);

        for(auto p:result_index){
            cout<< nums[p]<< " " ;
        }
        
        cout<< endl ;

        for(int i=k;i<nums.size();i++){




            // 抛弃上一个数据 如果上一个数据刚好是最大的
            if(!result_index.empty() && result_index.front()==i-k){
                result_index.pop_front();
            }

              // 5 3 4  - 5 4
            while(!result_index.empty() && nums[i]>nums[result_index.back()]){
                result_index.pop_back();
            }
            result_index.push_back(i);
            
            result.push_back(nums[result_index.front()]);


            for(auto p:result_index){
                cout<< nums[p]<< " " ;
            }
            cout<< endl ;

        }



        return result;  
    }
};

  队列 k=3 

 5 4 3 (4)-》剔除 小于当前值  5 4 剔除目前最大的索引为n-k  4 ,插入 4 4 最大 4

每次剔除确保了队列里前面都是比自己大的,队列保持递减顺序 

 

posted on 2025-10-08 20:00  MKT-porter  阅读(6)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3