Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit db54345

Browse files
heap: max in slide window
1 parent 8b720d0 commit db54345

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* @lc app=leetcode.cn id=239 lang=cpp
3+
*
4+
* [239] 滑动窗口最大值
5+
*
6+
* https://leetcode.cn/problems/sliding-window-maximum/description/
7+
*
8+
* algorithms
9+
* Hard (49.69%)
10+
* Likes: 2309
11+
* Dislikes: 0
12+
* Total Accepted: 443.7K
13+
* Total Submissions: 892.9K
14+
* Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
15+
*
16+
* 给你一个整数数组
17+
* nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的
18+
* k 个数字。滑动窗口每次只向右移动一位。
19+
*
20+
* 返回 滑动窗口中的最大值 。
21+
*
22+
*
23+
*
24+
* 示例 1:
25+
*
26+
*
27+
* 输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
28+
* 输出:[3,3,5,5,6,7]
29+
* 解释:
30+
* 滑动窗口的位置 最大值
31+
* --------------- -----
32+
* [1 3 -1] -3 5 3 6 7 3
33+
* ⁠1 [3 -1 -3] 5 3 6 7 3
34+
* ⁠1 3 [-1 -3 5] 3 6 7 5
35+
* ⁠1 3 -1 [-3 5 3] 6 7 5
36+
* ⁠1 3 -1 -3 [5 3 6] 7 6
37+
* ⁠1 3 -1 -3 5 [3 6 7] 7
38+
*
39+
*
40+
* 示例 2:
41+
*
42+
*
43+
* 输入:nums = [1], k = 1
44+
* 输出:[1]
45+
*
46+
*
47+
*
48+
*
49+
* 提示:
50+
*
51+
*
52+
* 1 <= nums.length <= 10^5
53+
* -10^4 <= nums[i] <= 10^4
54+
* 1 <= k <= nums.length
55+
*
56+
*
57+
*/
58+
59+
#include <queue>
60+
#include <utility>
61+
#include <vector>
62+
using namespace std;
63+
64+
// @lc code=start
65+
class Solution {
66+
public:
67+
// 大顶堆,每次遍历先入队,然后判断堆顶是否已经超出滑动窗口
68+
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
69+
vector<int> ret;
70+
ret.reserve(nums.size() - k);
71+
priority_queue<pair<int, int>> q;
72+
for (int i = 0; i < k; i++) {
73+
q.emplace(nums[i], i);
74+
}
75+
ret.push_back(q.top().first);
76+
for (int i = k; i < nums.size(); i++) {
77+
q.emplace(nums[i], i);
78+
while (q.top().second <= i - k) { // 上面已加,所以等于也要丢
79+
q.pop();
80+
}
81+
ret.push_back(q.top().first);
82+
}
83+
return ret;
84+
}
85+
};
86+
// @lc code=end

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /