-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeaps.java
More file actions
46 lines (40 loc) · 1.33 KB
/
Heaps.java
File metadata and controls
46 lines (40 loc) · 1.33 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
44
45
46
import java.util.Arrays;
import java.util.PriorityQueue;
public class Heaps {
static class Info implements Comparable<Info> {
int data;
int idx;
Info(int data, int idx) {
this.data = data;
this.idx = idx;
}
@Override
public int compareTo(Info s2) {
// return this.data - s2.data;
return s2.data - this.data;
}
}
public static void main(String[] args) {
// Maximum element in the k'size subarray
PriorityQueue<Info> pq = new PriorityQueue<>();
int[] ary = { -5, -3, 0, -5, 5, -1, 5 };
// int[] ary = Genarate_Random.generateRandomArray(20, -5, 5);
int k = 3;
int[] result = new int[ary.length - k + 1];
System.out.println(Arrays.toString(ary));
for (int i = 0; i < k; i++) {
pq.add(new Info(ary[i], i));
}
result[0] = pq.peek().data;
for (int i = 3, j = 1; i < ary.length; i++, j++) {
while (!pq.isEmpty() && pq.peek().idx <= (i - k))
pq.remove();
pq.add(new Info(ary[i], i));
result[j] = pq.peek().data;
}
String x[] = Arrays.toString(result).replaceAll("[\\[\\]]", "").split(",\\s*");
for (String y : x) {
System.out.print(y + " ");
}
}
}