Skip to content

Commit 4d74d95

Browse files
committed
feat: add solutions to lc problem: No.0239
No.0239.Sliding Window Maximum
1 parent 10dac3e commit 4d74d95

File tree

4 files changed

+263
-63
lines changed

4 files changed

+263
-63
lines changed

solution/0200-0299/0239.Sliding Window Maximum/README.md

+131-29
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,17 @@
4949

5050
<!-- 这里可写通用的实现逻辑 -->
5151

52-
**方法一:单调队列**
52+
**方法一:优先队列(大根堆)**
53+
54+
我们可以使用优先队列(大根堆)来维护滑动窗口中的最大值。
55+
56+
先将前 $k-1$ 个元素加入优先队列,接下来从第 $k$ 个元素开始,将新元素加入优先队列,同时判断堆顶元素是否滑出窗口,如果滑出窗口则将堆顶元素弹出。然后我们将堆顶元素加入结果数组。
57+
58+
时间复杂度 $O(n \times \log k)$,空间复杂度 $O(k)$。其中 $n$ 为数组长度。
59+
60+
**方法二:单调队列**
61+
62+
这道题也可以使用单调队列来解决。时间复杂度 $O(n)$,空间复杂度 $O(k)$。
5363

5464
单调队列常见模型:找出滑动窗口中的最大值/最小值。模板:
5565

@@ -70,6 +80,20 @@ for i in range(n):
7080

7181
<!-- 这里可写当前语言的特殊实现逻辑 -->
7282

83+
```python
84+
class Solution:
85+
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
86+
q = [(-v, i) for i, v in enumerate(nums[:k - 1])]
87+
heapify(q)
88+
ans = []
89+
for i in range(k - 1, len(nums)):
90+
heappush(q, (-nums[i], i))
91+
while q[0][1] <= i - k:
92+
heappop(q)
93+
ans.append(-q[0][0])
94+
return ans
95+
```
96+
7397
```python
7498
class Solution:
7599
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
@@ -90,6 +114,27 @@ class Solution:
90114

91115
<!-- 这里可写当前语言的特殊实现逻辑 -->
92116

117+
```java
118+
class Solution {
119+
public int[] maxSlidingWindow(int[] nums, int k) {
120+
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
121+
int n = nums.length;
122+
for (int i = 0; i < k - 1; ++i) {
123+
q.offer(new int[] {nums[i], i});
124+
}
125+
int[] ans = new int[n - k + 1];
126+
for (int i = k - 1, j = 0; i < n; ++i) {
127+
q.offer(new int[] {nums[i], i});
128+
while (q.peek()[1] <= i - k) {
129+
q.poll();
130+
}
131+
ans[j++] = q.peek()[0];
132+
}
133+
return ans;
134+
}
135+
}
136+
```
137+
93138
```java
94139
class Solution {
95140
public int[] maxSlidingWindow(int[] nums, int k) {
@@ -113,46 +158,47 @@ class Solution {
113158
}
114159
```
115160

116-
### **JavaScript**
161+
### **C++**
117162

118-
```js
119-
/**
120-
* @param {number[]} nums
121-
* @param {number} k
122-
* @return {number[]}
123-
*/
124-
var maxSlidingWindow = function (nums, k) {
125-
let ans = [];
126-
let q = [];
127-
for (let i = 0; i < nums.length; ++i) {
128-
if (q && i - k + 1 > q[0]) {
129-
q.shift();
130-
}
131-
while (q && nums[q[q.length - 1]] <= nums[i]) {
132-
q.pop();
163+
```cpp
164+
class Solution {
165+
public:
166+
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
167+
priority_queue<pair<int, int>> q;
168+
int n = nums.size();
169+
for (int i = 0; i < k - 1; ++i) {
170+
q.push({nums[i], -i});
133171
}
134-
q.push(i);
135-
if (i >= k - 1) {
136-
ans.push(nums[q[0]]);
172+
vector<int> ans;
173+
for (int i = k - 1; i < n; ++i) {
174+
q.push({nums[i], -i});
175+
while (-q.top().second <= i - k) {
176+
q.pop();
177+
}
178+
ans.emplace_back(q.top().first);
137179
}
180+
return ans;
138181
}
139-
return ans;
140182
};
141183
```
142184
143-
### **C++**
144-
145185
```cpp
146186
class Solution {
147187
public:
148188
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
149189
deque<int> q;
150190
vector<int> ans;
151191
for (int i = 0; i < nums.size(); ++i) {
152-
if (!q.empty() && i - k + 1 > q.front()) q.pop_front();
153-
while (!q.empty() && nums[q.back()] <= nums[i]) q.pop_back();
192+
if (!q.empty() && i - k + 1 > q.front()) {
193+
q.pop_front();
194+
}
195+
while (!q.empty() && nums[q.back()] <= nums[i]) {
196+
q.pop_back();
197+
}
154198
q.push_back(i);
155-
if (i >= k - 1) ans.push_back(nums[q.front()]);
199+
if (i >= k - 1) {
200+
ans.emplace_back(nums[q.front()]);
201+
}
156202
}
157203
return ans;
158204
}
@@ -162,9 +208,38 @@ public:
162208
### **Go**
163209

164210
```go
165-
func maxSlidingWindow(nums []int, k int) []int {
166-
var q []int
167-
var ans []int
211+
func maxSlidingWindow(nums []int, k int) (ans []int) {
212+
q := hp{}
213+
for i, v := range nums[:k-1] {
214+
heap.Push(&q, pair{v, i})
215+
}
216+
for i := k - 1; i < len(nums); i++ {
217+
heap.Push(&q, pair{nums[i], i})
218+
for q[0].i <= i-k {
219+
heap.Pop(&q)
220+
}
221+
ans = append(ans, q[0].v)
222+
}
223+
return
224+
}
225+
226+
type pair struct{ v, i int }
227+
228+
type hp []pair
229+
230+
func (h hp) Len() int { return len(h) }
231+
func (h hp) Less(i, j int) bool {
232+
a, b := h[i], h[j]
233+
return a.v > b.v || (a.v == b.v && i < j)
234+
}
235+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
236+
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
237+
func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
238+
```
239+
240+
```go
241+
func maxSlidingWindow(nums []int, k int) (ans []int) {
242+
q := []int{}
168243
for i, v := range nums {
169244
if len(q) > 0 && i-k+1 > q[0] {
170245
q = q[1:]
@@ -181,6 +256,33 @@ func maxSlidingWindow(nums []int, k int) []int {
181256
}
182257
```
183258

259+
### **JavaScript**
260+
261+
```js
262+
/**
263+
* @param {number[]} nums
264+
* @param {number} k
265+
* @return {number[]}
266+
*/
267+
var maxSlidingWindow = function (nums, k) {
268+
let ans = [];
269+
let q = [];
270+
for (let i = 0; i < nums.length; ++i) {
271+
if (q && i - k + 1 > q[0]) {
272+
q.shift();
273+
}
274+
while (q && nums[q[q.length - 1]] <= nums[i]) {
275+
q.pop();
276+
}
277+
q.push(i);
278+
if (i >= k - 1) {
279+
ans.push(nums[q[0]]);
280+
}
281+
}
282+
return ans;
283+
};
284+
```
285+
184286
### **...**
185287

186288
```

0 commit comments

Comments
 (0)