LeetCode 239: Sliding Window Maximum

239. Sliding Window Maximum

Difficulty: Hard
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position Max
———————– —
[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
Therefore, return the max sliding window as [3,3,5,5,6,7].

思路

使用双端队列存放当前滑动窗口的最大值,但是队列存放最大值时,若滑出窗口的数字为上一窗口的最大值,加入窗口的数字又比该值小,这时还需重新比较数字得出最大值。因此,队列需要把有可能成为最大值的数字存人队列。
以nums=[1,4,2,3,2,5],k=3为例,第一个滑动窗口的最大值为第二个数字4,第三个数字2虽然比队列中的4小,但当4滑出窗口后2可能当前窗口的最大值,因此2存入队列尾部。下一个数字3比2大,比4小,因此比2更可能成为4滑出窗口之后的最大值,从队列中删除2,添加3。最后一个数字是5,此时,队列中数字为3和2,5比3和2都大,3和2已经不可能成为滑动窗口的最大值,先把3和2从队列中删除,在存入5。这样,滑动窗口的最大值总是队列的头部。
此外,存数值的话无法判断滑动窗口是否包括该数字,因此在队列里存放数组下标,当数字下标与当前处理数字下标之差不小于滑动窗口大小时,表明该数字已从窗口滑出,可以从队列头部删除对应下标。

代码

[C++]

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> max;
        if (nums.size() <= 0 || k <= 0 || k >nums.size())
            return max;
        deque<int> index;
        for (int i = 0; i < k; ++i) {
            while (!index.empty() && nums[i] >= nums[index.back()])
                index.pop_back();
            index.push_back(i);
        }
        for (int i = k; i < nums.size(); ++i) {
            max.push_back(nums[index.front()]);
            if (!index.empty() && index.front() <= i - k)
                index.pop_front();
            while (!index.empty() && nums[i] >= nums[index.back()])
                index.pop_back();
            index.push_back(i);
        }
        max.push_back(nums[index.front()]);
        return max;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值