-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianStream.java
More file actions
36 lines (29 loc) · 884 Bytes
/
MedianStream.java
File metadata and controls
36 lines (29 loc) · 884 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
31
32
33
34
35
36
package priorityQueue;
import java.util.Collections;
import java.util.PriorityQueue;
/*
* Very Important Question For Interview.
* */
public class MedianStream {
private static final PriorityQueue<Integer> small = new PriorityQueue<>(Collections.reverseOrder());
private static final PriorityQueue<Integer> large = new PriorityQueue<>();
private static boolean even = true;
//Function to insert heap.
public static void insertHeap(int num) {
if (even) {
large.offer(num);
small.offer(large.poll());
} else {
small.offer(num);
large.offer(small.poll());
}
even = !even;
}
//Function to return Median.
public static double getMedian() {
if (even)
return (small.peek() + large.peek()) / 2.0;
else
return small.peek();
}
}