forked from kexun/sort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxWindow.java
49 lines (39 loc) · 1010 Bytes
/
MaxWindow.java
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
41
42
43
44
45
46
47
48
49
package com.demo;
import java.util.LinkedList;
/**
* 给定一个数组,arr和一个大小为w的窗口,从窗口的左边滑倒最右边,每次滑动一个位置,
* 如[4 3 5]4 3 3 6 7 最终返回的结果为5 5 5 4 6 7
* @author kexun
*
*/
public class MaxWindow {
public static void main(String[] args) {
int[] arr = {
4,3,5,4,3,3,6,7
};
MaxWindow w = new MaxWindow();
int[] result = w.getMaxWindow(arr, 3);
for (int i : result) {
System.out.println(i);
}
}
public int[] getMaxWindow(int[] arr, int w) {
int length = arr.length;
int[] result = new int[length-w+1];
LinkedList<Integer> list = new LinkedList<Integer>();
int index = 0;
for (int i=0; i<length; i++) {
while (!list.isEmpty() && arr[i] >= arr[list.peekLast()]) {
list.removeLast();
}
list.addLast(i);
if (list.peekFirst() == i - w) {
list.removeFirst();
}
if (i >= w -1 ) {
result[index++] = arr[list.peekFirst()];
}
}
return result;
}
}