Sliding Window Maximum

LeetCode #239


Description:

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.

Example:

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.

Follow up:
Could you solve it in linear time?

Idea:

Time: O(n), space O(k)

用一个deque,这个思想同样可以用于sliding window minimum.

void inQueue(deque<int>& DQ, int num){
    // change to DQ.back()>num, is for sliding window minimum
    while(!DQ.empty() && DQ.back()<num){
        DQ.pop_back();
    }
    DQ.push_back(num);
}

Code:

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int> DQ;
        vector<int> result;

        // 先弄k-1个
        for(int i=0; i<k-1; ++i){
            inQueue(DQ, nums[i]);
        }

        // 开始,先inQueue,再outQueue,中间存结果
        for(int i=k-1; i<nums.size(); ++i){
            inQueue(DQ, nums[i]);
            result.push_back(DQ.front());
            outQueue(DQ, nums[i-k+1]);
        }
        return result;
    }
    void inQueue(deque<int>& DQ, int num){
        while(!DQ.empty() && DQ.back()<num){
            DQ.pop_back();
        }
        DQ.push_back(num);
    }

    void outQueue(deque<int>& DQ, int num){
        if(DQ.front()==num)
            DQ.pop_front();
    }
};

results matching ""

    No results matching ""