forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSlidingWindow.java
More file actions
43 lines (38 loc) · 1.14 KB
/
MaxSlidingWindow.java
File metadata and controls
43 lines (38 loc) · 1.14 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
41
42
43
package map;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class MaxSlidingWindow {
public static void main(String[] args) {
int[] a = {1,3,-1,-3,5,3,6,7};
int k = 3;
int[] r = maxSlidingWindow(a,k);
System.out.println(Arrays.toString(r));
}
private static int[] maxSlidingWindow(int[] a, int k) {
if(a == null || k <= 0){
return new int[0];
}
int n = a.length;
int[] r = new int[n-k+1];
int ri = 0;
// store index
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
// remove numbers out of range k
while (!q.isEmpty() && q.peek() < i - k +1){
q.poll();
}
// remove smaller numbers in k range as they are useless
while(!q.isEmpty() && a[q.peekLast()] < a[i]){
q.pollLast();
}
// q contains index... r contains content
q.offer(i);
if (i >= k-1){
r[ri++] = a[q.peek()];
}
}
return r;
}
}