- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxWindow.java
More file actions
Latest commit
40 lines (38 loc) · 1.38 KB
/
Copy pathMaxWindow.java
File metadata and controls
40 lines (38 loc) · 1.38 KB
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
31
32
33
34
35
36
37
38
39
40
packagestack_and_queue;
importjava.util.LinkedList;
/**
* @Author: Wenhang Chen
* @Description:生成窗口最大值数组,返回数组res记录每个窗口的最大值
* @Date: Created in 20:02 10/30/2019
* @Modified by:
*/
publicclassMaxWindow {
// 用qmax队列存储窗口最大值的下标,队首为最大值下标,
// 如果qmax队尾的值比当前值小,则弹出队尾元素,重新
// 开始压入下标操作。如果队尾元素大于当前值,则继续压入
// 当前值的下标。
publicint[] getMaxWindow(int[] arr, intw) {
if (arr == null || w < 1 || arr.length < w) {
returnnull;
}
LinkedList<Integer> qmax = newLinkedList<>();
int[] res = newint[arr.length - w + 1];
intindex = 0;
for (inti = 0; i < arr.length; i++) {
while (!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[i]) {
qmax.pollLast();
}
qmax.addLast(i);
// 如果脱离窗口,则弹出。
if (qmax.peekFirst() == i - w) {
qmax.pollFirst();
}
// 即使小也压入是因为当前面的元素离开窗口后,后来的
// 元素可能成为最大值。
if (i >= w - 1) {
res[index++] = arr[qmax.peekFirst()];
}
}
returnres;
}
}