1. 程式人生 > >LeetCode OJ 之 Sliding Window Maximum(滑動視窗的最大值)

LeetCode OJ 之 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.

Follow up:
Could you solve it in linear time?

思路:

這裡可以使用雙端佇列,使得佇列裡的數呈遞減趨勢,即始終保持隊頭最大。

如果對頭在當前視窗內,則它就是當前視窗的最大值。

如果隊頭不在當前視窗範圍,則刪除它。這裡佇列裡儲存的不是值,而是值的位置,因為如果儲存值的話,無法判斷值是否在當前視窗中。

程式碼:

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) 
    {
        deque<int> dq;
        vector<int> result;
        int len = nums.size();

        for (int i = 0 ; i < len ; i++) 
        {
             //當前視窗是[i-k+1, i-k+2, ... i-1, i ](i>=k-1時),如果隊頭不在這個範圍內,則丟棄
            if (!dq.empty() && dq.front() < i-k+1) 
                dq.pop_front();
                
            //把佇列中小的刪掉,保持佇列遞減
            while (!dq.empty() && nums[dq.back()] < nums[i])
                dq.pop_back();
                
            dq.push_back(i);
            
            //從k-1開始,每次的隊頭就是最大值
            if (i >= k-1) 
                result.push_back(nums[dq.front()]);
        }
        return result;
    }

};

上面deque的操作list也都有,可以替換成list。