class MedianFinder {
// |<a a | b >b|
// smallHalf LargeHalf
private PriorityQueue<Integer> smallHalf;
private PriorityQueue<Integer> largeHalf;
/** initialize your data structure here. */
public MedianFinder() {
this.smallHalf = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
this.largeHalf = new PriorityQueue<>();
}
public void addNum(int num) {
// num -> smallHalf
// largeHalf <- smallHalf.top()
// largeHalf.top() ->
smallHalf.add(num);
largeHalf.add(smallHalf.peek());
smallHalf.poll();
if (smallHalf.size() < largeHalf.size()) {
smallHalf.add(largeHalf.poll());
}
}
public double findMedian() {
if (smallHalf.size() > largeHalf.size()) {
return (double) smallHalf.peek();
} else {
return (double) (smallHalf.peek() + largeHalf.peek()) / 2.0;
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/