• 欢迎光临~

# 239. 滑动窗口最大值(最大堆)

#### 239. 滑动窗口最大值

```输入：nums = [1,3,-1,-3,5,3,6,7], k = 3

---------------               -----
[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
```

```输入：nums = [1], k = 1

```

• `1 <= nums.length <= 105`
• `-104 <= nums[i] <= 104`
• `1 <= k <= nums.length`
``` 1 class Solution {
2 public:
3     vector<int> maxSlidingWindow(vector<int>& nums, int k) {
4         vector<int> ans;
5         if (nums.empty() || k == 0) {
6             return ans;
7         }
8         priority_queue<std::pair<int, int>> pq; // 最大堆
9         for (unsigned int i = 0; i < k; i++) {
10             pq.push({nums[i], i});
11         }
12         ans.emplace_back(pq.top().first); // 第一组k个元素中最大值
13         for (unsigned int i = k; i < nums.size(); i++) {
14             // 当剩余n-k个元素中两元素间距不小于最大堆堆顶元素的下标时,说明为下一组k个元素,需要丢弃堆顶元素
15             while (!pq.empty() && pq.top().second <= i - k) {
16                 pq.pop();
17             }
18             pq.push({nums[i], i});
19             ans.emplace_back(pq.top().first);
20         }
21         return ans;
22     }
23 };```