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


最最簡單的暴力brute force方法就是遍歷整個數組的時候,對當前開始的size爲k的window取最大。取最大可以簡單粗暴地遍歷一遍進行比較,這樣是O(nk)的複雜度,但也可以直接用個heap來存然後取最top,也就是降到了O(nlogk)的複雜度。代碼如下:

Runtime: 1700 ms, faster than 5.20% of C++ online submissions for Sliding Window Maximum.

Memory Usage: 179.7 MB, less than 6.56% of C++ online submissions for Sliding Window Maximum.

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        if (nums.empty()) {
            return vector<int>();
        }
        vector<int> result;
        for (int i = 0; i < nums.size() - k + 1; i++) {
            priority_queue<int> window(nums.begin() + i, nums.begin() + i + k);
            result.push_back(window.top());
        }
        return result;
    }
};

另一種方法是採用deque,deque是雙向隊列,可以在任意一端進行push和pop。採用deque的思想在於,我們在deque中存放一段在window size範圍內的非遞增序列,每次遇到新的數字都把它push到deque裏,並且如果這個數字比deque中的某些數字大,就把比它小的都pop掉,最後每次iteration的時候deque裏的front就是目前window size中最大的元素。需要注意的就是要保證deque中的front一定要在window size範圍內(對於這個實現方式的理解還需要更深刻一些)。https://www.zhihu.com/question/314669016/answer/663930108 這個鏈接中有很好的動畫展示,真的非常易懂。

Runtime: 56 ms, faster than 86.96% of C++ online submissions for Sliding Window Maximum.

Memory Usage: 13.1 MB, less than 77.05% of C++ online submissions for Sliding Window Maximum.

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        if (nums.empty()) {
            return vector<int>();
        }
        vector<int> result;
        deque<int> dq;
        for (int i = 0; i < nums.size(); i++) {
            // should use dq.back() because it might be smaller than first
            // but larger than remaining
            while (!dq.empty() && nums[i] > dq.back()) {
                dq.pop_back();
            }
            dq.push_back(nums[i]);
            if (i >= k - 1) {
                result.push_back(dq.front());
                // if the current front is the first elem in the window
                // we cannot keep it in the next iteration, so pop it
                if (nums[i - k + 1] == dq.front()) {
                    dq.pop_front();
                }
            }
        }
        
        return result;
    }
};

最後一種方法是有一點動態規劃的思想。我們先把整個數組分成大小爲k的幾組,最後一組的個數可以小於k。然後我們分別對每組中的元素求出從左到右的max和從右到左的max(有那麼一點點像trapping rain water)。我們在slide整個數組的時候,這個window可能有兩種情況,一種是所有元素都在剛剛分出來的同一個組中,另一種是分別在兩個不同的組中:

split

假如當前的窗口是從i到j,並且i是某一組的起始元素,那麼當前window的max就是left[j]或者right[i]

假如i不是起始元素,那麼一定是第二種情況,那麼當前window的max應該是max(left[j], right[i])

兩種情況可以合併,其實就直接是max(left[j], right[i])

Runtime: 56 ms, faster than 86.96% of C++ online submissions for Sliding Window Maximum.

Memory Usage: 14.3 MB, less than 22.95% of C++ online submissions for Sliding Window Maximum.

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        if (nums.empty()) {
            return vector<int>();
        }
        vector<int> result, left, right;
        int max_left, max_right;
        for (int i = 0; i < nums.size(); i++) {
            if (i % k == 0) {
                max_left = nums[i];
            }
            else {
                max_left = max(max_left, nums[i]);
            }
            left.push_back(max_left);
        }
        
        for (int i = nums.size() - 1; i >= 0; i--) {
            if (i % k == 0) {
                max_right = nums[i];
            }
            else {
                max_right = max(max_right, nums[i]);
            }
            right.push_back(max_right);
        }
        reverse(right.begin(), right.end());
        
        for (int i = 0; i < nums.size() - k + 1; i++) {
            result.push_back(max(left[i + k - 1], right[i]));
        }
        return result;
    }
};

上面代碼中進行了兩次for循環得到left和right數組,其實可以放在一個循環裏,但是懶得寫了……

發佈了123 篇原創文章 · 獲贊 1 · 訪問量 9375
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章