-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedianOfStream.java
68 lines (59 loc) · 1.92 KB
/
MedianOfStream.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class MedianOfStream {
public Queue<Integer> minHeap;
public Queue<Integer> maxHeap;
public int numElements;
public MedianOfStream(){
minHeap = new PriorityQueue<Integer>();
maxHeap = new PriorityQueue<Integer>(10,new MaxHeapComparator());
numElements = 0;
}
public void addNumberToStream(Integer num){
maxHeap.add(num);
if(numElements %2 == 0){
if(minHeap.isEmpty()){
numElements++;
return;
}
else if(maxHeap.peek() > minHeap.peek() ){
Integer maxHeapRoot = maxHeap.poll();
Integer minHeapRoot = minHeap.poll();
maxHeap.add(minHeapRoot);
minHeap.add(maxHeapRoot);
}
}else{
minHeap.add(maxHeap.poll());
}
numElements++;
}
public Double getMedian(){
if (numElements%2 != 0){
return new Double(maxHeap.peek());
}
else{
return (maxHeap.peek()+minHeap.peek())/2.0;
}
}
private class MaxHeapComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2){
return o2-o1;
}
}
public static void main(String[] args) {
MedianOfStream streamMedian = new MedianOfStream();
streamMedian.addNumberToStream(1);
System.out.println(streamMedian.getMedian()); // should be 1
streamMedian.addNumberToStream(5);
streamMedian.addNumberToStream(10);
streamMedian.addNumberToStream(12);
streamMedian.addNumberToStream(2);
System.out.println(streamMedian.getMedian()); // should be 5
streamMedian.addNumberToStream(3);
streamMedian.addNumberToStream(8);
streamMedian.addNumberToStream(9);
System.out.println(streamMedian.getMedian()); // should be 6.5
}
}