239. Sliding Window Maximum (滑动窗口最大值, 大根堆)

 

You are given an array of integers 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.

 

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], 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

 

 

 1 class Solution {
 2 public:
 3     vector<int> maxSlidingWindow(vector<int>& nums, int k) {
 4         vector<int> res;
 5         priority_queue<pair<int, int>> q;
 6         for(int i = 0; i < k;++i) {
 7             q.push({nums[i],i});
 8         }
 9         res.push_back(q.top().first);
10 
11         for(int i = k;i < nums.size();++i) {
12             q.push({nums[i],i});
13             while(q.top().second + k <= i) {
14                 q.pop();
15             }
16             res.push_back(q.top().first);
17         }
18         return res;
19     }
20 };

 

239. Sliding Window Maximum (滑动窗口最大值, 大根堆)

上一篇:Android 在Fragment中执行onActivityResult不被调用的简单解决方法


下一篇:ios 烟花 火焰 雨水 雪花等特效属性