题目描述:
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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
利用滑动窗口,求窗口的最大值。利用双向队列维持一个单减的滑动窗口,这样窗口最大值就在窗口的头部。但是为了控制窗口的大小,我们用滑动窗口存储下标,而不是元素值,这样每次滑动窗口进入一个数,都可以和滑动窗口的头部元素比较下标,来确定滑动窗口的最大值是不是还在窗口内,如果头部元素已经超出了窗口范围,就把它删除,那么它之后的元素变为窗口的最大值。同时为了能够以O(1)的时间复杂度得到滑动窗口的最大值,我们需要始终保持滑动窗口是一个单减序列,也就是在滑动窗口每次进入一个数之后,都要从窗口尾部开始,把所有比当前元素小的数全部删除。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> result;
deque<int> q;
for(int i=0;i<nums.size();i++)
{
if(!q.empty()&&q.front()==i-k) q.pop_front();
if(q.empty()) q.push_back(i);
else
{
while(!q.empty()&&nums[q.back()]<nums[i]) q.pop_back();
q.push_back(i);
}
if(i>=k-1) result.push_back(nums[q.front()]);
}
return result;
}
};
本文介绍了一种求解滑动窗口最大值的高效算法,使用双向队列维护单减序列,实现在线性时间内解决问题。通过实例展示了算法的具体实现过程。

被折叠的 条评论
为什么被折叠?



