1. 程式人生 > 實用技巧 >【刷題-LeetCode】239. Sliding Window Maximum

【刷題-LeetCode】239. Sliding Window Maximum

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

Follow up:
Could you solve it in linear time?

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

很奇怪很多答案為什麼又是堆又是雜湊表的。。。

用一個tmp_max變數記錄窗口裡的最大值,向右移動時,如果最左邊出去的是最大值tmp_max,就在窗口裡重新線性搜尋或者呼叫max_element()或者其他什麼方法找到最大值,右端點進來的新的值和tmp_max比較一下取大的作為新的tmp_max

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int l = 0, r = k;
        vector<int>ans;
        int tmp = INT_MIN;
        for(int i = 0; i < r; ++i)tmp = max(nums[i], tmp);
        ans.push_back(tmp);
        r++;
        l++;
        while(r <= nums.size()){
            if(tmp == nums[l-1]){
                tmp = INT_MIN;
                for(int i = l; i < r; ++i)tmp = max(tmp, nums[i]);
            }else{
                tmp = max(tmp, nums[r-1]);
            }
            ans.push_back(tmp);
            l++;
            r++;
        }
        return ans;
    }
};