239. Maximum sliding window (priority queue)

Given an integer array nums, there is a sliding window of size k that moves from the leftmost side of the array to the rightmost side of the array. You can only see the k numbers in the sliding window. The sliding window only moves one position to the right at a time.

Returns the maximum value in the sliding window.

 

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
The position of the sliding window Maximum
--------------- -----
[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
Example 2 :

Input: nums = [1], k = 1
Output: [1]

analysis:

The main thing is to learn to use priority_queue. Compared with ordinary queues, emplace can be used to ensure that the top element is the maximum value. The code is as follows

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int n = nums.size();
        priority_queue<pair<int, int>> q;
        // 前k个构造一下优先队列
        for(int i = 0; i < k; i++){
            q.emplace(nums[i], i);
            // 大顶堆,这个top对应的就是前k个里面最大的,从大到小的一个队列
            // cout << q.top().first << " " << q.top().second ;
        }
        // 构造一个数组专门装每次窗口的最大值
        vector<int> resultMax;
        resultMax.push_back(q.top().first);
        for(int i = k; i < nums.size(); i++){
            q.emplace(nums[i], i);
            // 为的是,假如后面窗口中的最大值比前面窗口的最大值小,那么堆顶一直都是原来窗口的最大值,需要把这些值给及时的pop掉,同样也能减轻堆的大小,比如[1, -1] k = 1这类情况
            while(q.top().second <= i - k){
                q.pop();
            }
            resultMax.push_back(q.top().first);
        }
        return resultMax;
    }
};


Guess you like

Origin blog.csdn.net/qq_34612223/article/details/113836273