leetcode-239-Sliding Window Maximum

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.

求滑动窗口括起来的数组中的最大值。

1
2
3
4
Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]

Explanation:

1
2
3
4
5
6
7
8
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?

先建立一个双端队列,然后每加入一个元素都把队列中这个元素之前的比这个元素小的值给删除,因为他们不可能是最大值了,这样维持了双端队列中从左至右元素依次递减的特性(最大的就在队列第一个位置),每次新加入元素前,检测队列里第一个元素之是否已经移出窗口,然后再进行操作。队列里存放的是数组里值对应的下标,这样方便计算队列首元素是否已经滑出窗口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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++){
/*** remove the top element 检测队列里第一个元素之是否已经移出窗口**/
if(!q.empty() && q.front()==i-k) q.pop_front();
/*** keep the element in the queue is monotically-decreasing ***/
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;
}
};
Donate? comment?