Sword Finger Offer 59-I. Maximum sliding window

Given an array nums and the size of the sliding window k, please find the maximum value among all sliding windows.

Example:

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

Maximum position of the sliding window


[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

prompt:

You can assume that k is always valid, and if the input array is not empty, 1 ≤ k ≤ the size of the input array.

The maximum value of the fixed length, using deque double-ended queue to achieve the update of the head and tail elements

Maintain a sequence from largest to smallest, that is, delete all values ​​smaller than the current value from the tail, and then put the current value

When i>=k-1, the head element starts to pop up-the maximum value

If the maximum value is [i-k+1, i ], the first window of length K is i-k+1, then for the next window [i-k+2, i+1] Just need to delete

class Solution {
    
    
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
    
    
        vector<int>ve;
        deque<int>de;
        for(int i=0;i<nums.size();i++)
        {
    
    
            while((!de.empty())&&nums[de.back()]<nums[i]) de.pop_back();

            de.push_back(i);

            if(i>=k-1)    //开始在范围内找最大值
            {
    
    
                ve.push_back(nums[de.front()]);   //目前已知的最大值

                if(de.front()==i-k+1) de.pop_front();   //更新如果刚好是这个窗口第一个
            }
        }
        return ve;
    }
};

Guess you like

Origin blog.csdn.net/qq_43624038/article/details/113794399