-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain239.java
More file actions
30 lines (28 loc) · 933 Bytes
/
Main239.java
File metadata and controls
30 lines (28 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package HOT100;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main239 {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
// 二元组 (num, index) 表示元素 num 在数组中的下标为 index
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] != o2[0] ? o2[0] - o1[0] : o2[1] - o1[1];
}
});
for (int i = 0; i < k; i++) {
pq.offer(new int[]{nums[i], i});
}
int[] ans = new int[n - k + 1];
ans[0] = pq.peek()[0];
for (int i = k; i < n; i++) {
pq.offer(new int[]{nums[i], i});
while (pq.peek()[1] <= i - k) {
pq.poll();
}
ans[i - k + 1] = pq.peek()[0];
}
return ans;
}
}