forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0295-find-median-from-data-stream.java
40 lines (36 loc) · 1.19 KB
/
0295-find-median-from-data-stream.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
class MedianFinder {
private Queue<Integer> smallHeap; //small elements - maxHeap
private Queue<Integer> largeHeap; //large elements - minHeap
public MedianFinder() {
smallHeap = new PriorityQueue<>((a, b) -> b - a);
largeHeap = new PriorityQueue<>((a, b) -> a - b);
}
public void addNum(int num) {
smallHeap.add(num);
if (
smallHeap.size() - largeHeap.size() > 1 ||
!largeHeap.isEmpty() &&
smallHeap.peek() > largeHeap.peek()
) {
largeHeap.add(smallHeap.poll());
}
if (largeHeap.size() - smallHeap.size() > 1) {
smallHeap.add(largeHeap.poll());
}
}
public double findMedian() {
if (smallHeap.size() == largeHeap.size()) {
return (double) (largeHeap.peek() + smallHeap.peek()) / 2;
} else if (smallHeap.size() > largeHeap.size()) {
return (double) smallHeap.peek();
} else {
return (double) largeHeap.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/