
Solution
- Use two heap, to store the smaller half and the bigger half.
- leftHalf->maxHeap, rightHalf->minHalf
- if odd, make sure rightHalf always have 1 more than leftHalf. This case, the 1 more is the median
- if even, it's the avg of two peek
class MedianFinder {
PriorityQueue<Integer> rightHalf;
PriorityQueue<Integer> leftHalf;
public MedianFinder() {
rightHalf = new PriorityQueue<>();
leftHalf = new PriorityQueue<>((a, b) -> (b - a));
}
public void addNum(int num) {
if (leftHalf.size() == rightHalf.size()) {
leftHalf.add(num);
rightHalf.add(leftHalf.poll());
} else {
rightHalf.add(num);
leftHalf.add(rightHalf.poll());
}
}
public double findMedian() {
if (leftHalf.size() == rightHalf.size()) {
return (leftHalf.peek() + rightHalf.peek()) / 2.0;
} else {
return rightHalf.peek();
}
}
}