Skip to content

Commit 609ac9b

Browse files
authored
Update 0239.滑动窗口最大值 Java Solution
Add Java Solution with Priority Queue Solution.
1 parent 703a500 commit 609ac9b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

problems/0239.滑动窗口最大值.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,9 @@ class Solution {
260260
return res;
261261
}
262262
}
263+
```
263264

265+
```Java
264266
//解法二
265267
//利用双端队列手动实现单调队列
266268
/**
@@ -296,6 +298,39 @@ class Solution {
296298
}
297299
```
298300

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+
299334
### Python:
300335
#### 解法一:使用自定义的单调队列类
301336
```python

0 commit comments

Comments
 (0)