forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
42 lines (35 loc) · 1.18 KB
/
Solution.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
class MedianFinder {
private PriorityQueue<Integer> bigRoot;
private PriorityQueue<Integer> smallRoot;
/** initialize your data structure here. */
public MedianFinder() {
bigRoot = new PriorityQueue<>(Comparator.reverseOrder());
smallRoot = new PriorityQueue<>(Integer::compareTo);
}
public void addNum(int num) {
if (bigRoot.isEmpty() || bigRoot.peek() > num) {
bigRoot.offer(num);
} else {
smallRoot.offer(num);
}
int size1 = bigRoot.size();
int size2 = smallRoot.size();
if (size1 - size2 > 1) {
smallRoot.offer(bigRoot.poll());
} else if (size2 - size1 > 1) {
bigRoot.offer(smallRoot.poll());
}
}
public double findMedian() {
int size1 = bigRoot.size();
int size2 = smallRoot.size();
return size1 == size2 ? (bigRoot.peek() + smallRoot.peek()) * 1.0 / 2
: (size1 > size2 ? bigRoot.peek() : smallRoot.peek());
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/