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.

Example:

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

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?

思路:

因为是一个滑动窗口,可以立即想到利用队列(queue)。

但是在这里,我们要保证队列里的是可能的最大值,所以我们要把当前值与队列里的值进行比较,且是从左向右比较,所以我们需要尾部也能够有元素进出。

此时我们需要deque(双端队列),顾名思义,可以在两段进行元素的进出。

左端判断该值是否还在滑动窗口范围内,若不在,则弹出(pop_front)

右端入队时需要跟队列尾部元素进行比较,若尾部元素比它小,则尾部不可能成为最大值,弹出。

一开始我会想,这样弹出会不会影响到前面滑动窗口的最大值?是不会的,因为我们左端会对出现在滑动窗口里的值进行维护,保证现在队列里的值都会出现在一个滑动窗口中。

代码:

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

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9124093.html
今日推荐