leetcode 239. 滑动窗口最大值(单调队列)

给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回滑动窗口中的最大值。

进阶:

你能在线性时间复杂度内解决此题吗?

示例:

输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:

滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
 

提示:

1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sliding-window-maximum

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int>a;
        deque<int>b;
        vector<int>s;
        for(int i=0;i<k-1;i++){
            while(!a.empty()&&a.back()<=nums[i]){
                a.pop_back();
                b.pop_back();
            }
            a.push_back(nums[i]);
            b.push_back(i);
        }
        for(int i=k-1;i<nums.size();i++){
            while(!a.empty()&&a.back()<=nums[i]){
                a.pop_back();
                b.pop_back();
            }
            a.push_back(nums[i]);
            b.push_back(i);

            while(b.front()<=i-k){
                a.pop_front();
                b.pop_front();
            }
            s.push_back(a.front());
        }
        return s;
    }
};
扫描二维码关注公众号,回复: 10263290 查看本文章

猜你喜欢

转载自www.cnblogs.com/wz-archer/p/12590056.html