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. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
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 |
解题思路
这道题使用我使用一个数据结构deque进行记录当前窗口内的数值,这个空间类似队列,队列头部存放当前窗口中的最大值对应的数组下标,并且保证队列中的其他元素必定小于等于该下标对应的数组元素的值。
算法共四步:
1、对原始数组进行遍历,对于每个数组元素做下列操作
2、若当前扫描的数组下标与队列头部存放的数组下标的距离大于等于k,那么说明此时队列头部存放的数组下标已经离开可视窗口,因此需要将其移出队列。重复以上操作直到确保所有的下标都在窗口内。
3、从队列尾部开始遍历,如果队列尾部存放的数组下标所对应的数组元素的值小于等于新增加(当前扫描到的数组下标)的值,那么将其移出队列。因为对于原队列来说,新入队的元素可以被认为是整个队列的最小值,其他小于这个新值的队列元素不可能在新的窗口中成为最大值,因此可以被移出队列。极端情况下,这个新值就是当前新窗口区间的最大值。
4、将新值保存至队列中。若此时窗口的长度为k,那么将队列头部保存的下标所对应的数组元素(即当前窗口的最大值)保存至结果数组。完成遍历后将结果数组返回。
C++代码
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> rec;
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
while(!rec.empty() && i - rec.front() >= k) rec.pop_front();
while(!rec.empty() && nums[i] >= nums[rec.back()]) rec.pop_back();
rec.push_back(i);
if(i >= k-1){
res.push_back(nums[rec.front()]);
}
}
return res;
}
};