Sword Finger Offer 59-I. Maximum Sliding Window (C++) Monotonic Queue

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

Example:

输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7] 
解释: 

  滑动窗口的位置                最大值
---------------               -----
[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.

Note: This question is the same as question 239 of the main website: https://leetcode-cn.com/problems/sliding-window-maximum/

Problem-solving ideas

Reference idea: https://blog.csdn.net/qq_30457077/article/details/113092349

class Solution {
    
    
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
    
    
        int n = nums.size();
        deque<int> q;//双端队列
        // for (int i = 0; i < k; ++i) {
    
    
        //     while (!q.empty() && nums[i] >= nums[q.back()]) {
    
    
        //         q.pop_back();
        //     }
        //     q.push_back(i);
        // }
        vector<int> ans;
        //两种特殊情况
        if(k == 1)  return vector<int>(nums.begin(), nums.end());
        if(n == 0 || k > n)
            return ans;
        
        for (int i = 0; i < n; ++i) {
    
    
            while (!q.empty() && nums[i] >= nums[q.back()]) {
    
    
                q.pop_back();//当前数大于以队列尾为索引的数,队列弹出该索引;
                //从而获取递减的双端队列
            }
            q.push_back(i);//当前索引推入队列
            while ( q.front() <= i - k) {
    
    //队列头超出窗口大小,队列头出列
                q.pop_front();
            }
            //当i>=k-1才获取双端队列的头
            if(i>=k-1)
            {
    
    
            //满足窗口大小,可以获取队列头部
            ans.push_back(nums[q.front()]);
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114645538