题目链接:https://leetcode.com/problems/sliding-window-maximum/#/description
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].
The basic idea is to use a deque (buffer) to save all currently potential "maximum" elements (i.e. the element in the current k-element window [i-k+1, i], and it is larger than the elements after itself). So for each i, we first pop up the elements that are no larger than nums[i] from buffer until we find one that is larger than nums[i] or the buffer is empty since those elements will be covered by nums[i] and can not be a maximum of any k-element window. Then we put nums[i] in the buffer. If i>=k-1, we need to ouput the maximum for window [i-k+1, i], which is the front element of buffer. At last, we will check if the front element is nums[i-k+1], if so, we have to pop it up since it will be out of the window [i-k+2, i+1] in the next iteration. Since all the elements will be pushed into/ popped out of the buffer only once, so the time complexity is O(N).
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> buffer;
vector<int> res;
for(auto i=0; i<nums.size();++i)
{
while(!buffer.empty() && nums[i]>=nums[buffer.back()]) buffer.pop_back();
buffer.push_back(i);
if(i>=k-1) res.push_back(nums[buffer.front()]);
if(buffer.front()== i-k + 1) buffer.pop_front();
}
return res;
}
};

本文介绍了一种高效求解滑动窗口最大值问题的方法,使用双端队列存储潜在的最大元素,确保每次滑动更新时能快速找到窗口内的最大值。通过具体实例展示了算法流程,并提供了C++实现代码。
3万+

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



