File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -260,7 +260,9 @@ class Solution {
260
260
return res;
261
261
}
262
262
}
263
+ ```
263
264
265
+ ``` Java
264
266
// 解法二
265
267
// 利用双端队列手动实现单调队列
266
268
/**
@@ -296,6 +298,39 @@ class Solution {
296
298
}
297
299
```
298
300
301
+ ``` Java
302
+ // 解法三
303
+ // 用优先队列 Priority Queue, 时间Time: O(nlogk) | 空间Space: O(k)
304
+ /**
305
+ * 很好理解,PQ 会优先置顶最大值(Java Comparator)
306
+ * 维护window里的 PQ, PQ内部记录 <value, index> pair
307
+ **/
308
+ class Solution {
309
+ public int [] maxSlidingWindow (int [] nums , int k ) {
310
+ if (nums == null || k <= 0 )
311
+ return new int [0 ];
312
+
313
+ int n = nums. length;
314
+ int [] res = new int [n - k + 1 ];
315
+ PriorityQueue<int[]> maxHeap = new PriorityQueue<> ((a, b) - > b[0 ] - a[0 ]);
316
+
317
+ for (int i = 0 ; i < n; i++ ) {
318
+ maxHeap. offer(new int [] { nums[i], i });
319
+
320
+ // 删除窗口之外的元素
321
+ while (maxHeap. peek()[1 ] <= i - k) {
322
+ maxHeap. poll();
323
+ }
324
+
325
+ if (i >= k - 1 ) {
326
+ res[i - k + 1 ] = maxHeap. peek()[0 ];
327
+ }
328
+ }
329
+ return res;
330
+ }
331
+ }
332
+ ```
333
+
299
334
### Python:
300
335
#### 解法一:使用自定义的单调队列类
301
336
``` python
You can’t perform that action at this time.
0 commit comments