原题:
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]
.
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
解决方法:
用一个队列来保存数的序号。
- 对数组中的每一个数,将队列尾部小于该数的序号都弹出。然后将当前序号加入到队列中。
- 从第k个数开始,需要将队列最前面的那个数加入到结果集中。
- 如果队列最前面的数超过当前窗口的范围,需要弹出最前面的序号。
代码:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int len = nums.size();
vector<int> res;
deque<int> d;
for(int i = 0; i < len; i++){
while(!d.empty() && nums[i] >= nums[d.back()])
d.pop_back();
d.push_back(i);
if (i >= k - 1)
res.push_back(nums[d.front()]);
if (d.front() <= i - k + 1)
d.pop_front();
}
return res;
}