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].

 

思路: 单调双端队列。

维护一个单调双端队列,每次遍历到一个数字的时候,从队列的尾端依次pop出比当前小的数。 

如果队列的第一个元素到当前的位置距离大于k,那么应该pop出。

队列中的第一个元素就是当前的最大值。

AC代码:

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> ret;
        deque<int> q;
        for(int i=0; i<nums.size(); i++)
        {
            while(!q.empty() && nums[q.back()] <= nums[i])
                q.pop_back();
            q.push_back(i);
            if(i-q.front()+1 > k)
            {
                q.pop_front();
            }
            if(i >= k-1)
            {
                ret.push_back(nums[q.front()]);
            }
        }
        return ret;
    }
};

 

posted @ 2016-03-26 14:06  Gu Feiyang  阅读(147)  评论(0)    收藏  举报