Sword Finger Offer Series Sword Finger Offer 59-I: Maximum sliding window

Title description:

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: 

  The position of the sliding window Maximum value
--------------- -----
[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

Problem-solving ideas:

Mainly use the queue to save the maximum value of the sliding window

step:

  1. First determine whether the position of the head of the team is within the sliding window minus 3 from the current position, if not, remove the head
  2. Compare the value of the current position with the value of the entire queue, and remove all values ​​in the queue that are less than the current position (to ensure that the queue is a monotonic queue from large to small)
  3. Enqueue the value of the current position
  4. Put the head of the queue into the array and return to step 1.

Illustration:

The first two times are not shown in the figure,

  1. Position 0 in the first training
  2. In the second loop, position 1 is greater than position 0, so when step 2 is judged, position 1 is out of the queue, and position 1 is the head of the queue at this time, and put it into the array
  3. Position 2 is less than position 1, so position 2 is added to the queue; position 1 at the head of the queue is put into the array.

Code:

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& num, int k) {
        vector<int> res;   //存储所有滑动窗口里数值的最大值
        deque<int> q;   //存储滑动窗口里的数据
        for(int i=0;i<num.size();i++)
        {
            //滑动窗口满时,则队头出队列
            while(!q.empty() && i-q.front() >= k)
            {
                q.pop_front();
            }
            //维持队列的单调性
            while(!q.empty() && num[i]>=num[q.back()])
            {
                q.pop_back();
            }
            q.push_back(i);
            if(i>=k-1)
            {
                res.push_back(num[q.front()]);
            }
        }
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/111190709