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.
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.
解题思路:本题利用deque来对问题进行求解。利用deque来存储nums元素的索引index,注意保存的index所对应的nums[index]的值应该是从大到小排列的,处理的方法就是若处理的nums[i]的值小于deque.back()索引对应的元素的值,则直接丢弃,若处理的nums[i]的值大于等于deque.back()索引对应的元素的值,则弹出deque的尾部元素,继续比较直到deque为空或者nums[i]的值于小于deque.back()索引对应的元素的值,此时将i加入到deque的尾部。需要注意的是当处理长度达到窗的长度是deque.front()索引对应的元素即为最大值,当最大值对应的索引滑出窗外时要弹出最大值。
class Solution
{
public:
vector<int> maxslidingWindow(vector<int>& nums, int k)
{
vector<int> ans;
deque<int> dq;
for (int i = 0; i < nums.size(); ++i)
{
while (!dq.empty() && nums[dq.back()] <= nums[i])dq.pop_back();
dq.push_back(i);
if (i >= k - 1) ans.push_back(nums[dq.front()]); //在ans中加入最大值
if (dq.front() <= i - k + 1) dq.pop_front(); //最大值将滑出窗外,应该弹出
}
return ans;
}
};