LeetCode刷题实战239:滑动窗口最大值
You are given an array of integers 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.
示例
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[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
示例 2:
输入:nums = [1], k = 1
输出:[1]
示例 3:
输入:nums = [1,-1], k = 1
输出:[1,-1]
示例 4:
输入:nums = [9,11], k = 2
输出:[11]
示例 5:
输入:nums = [4,-2], k = 2
输出:[4]
解题
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> result;
int n = nums.size();
if(n<k) return result;
deque<int> que;
for(int i=0;i<k;++i){
while(!que.empty() && nums[que.back()]<nums[i])
{
que.pop_back();
}
que.push_back(i);
}
result.push_back(nums[que.front()]);
for(int i=k;i<n;++i){
while(!que.empty() && nums[que.back()]<nums[i])
{
que.pop_back();
}
if(!que.empty() && i-que.front()>=k)
que.pop_front();
que.push_back(i);
result.push_back(nums[que.front()]);
}
return result;
}
};