Two heaps
Time O(log n) add, O(1) median Space O(n)addNum: push into low, move low's top to high, and if high is bigger move its top back. findMedian: low's top, or the average of both tops.
import java.util.*;
class MedianFinder {
private final PriorityQueue<Integer> low = new PriorityQueue<>(Comparator.reverseOrder());
private final PriorityQueue<Integer> high = new PriorityQueue<>();
public MedianFinder() {}
public void addNum(int num) {
low.offer(num);
high.offer(low.poll());
if (high.size() > low.size()) low.offer(high.poll());
}
public double findMedian() {
return low.size() > high.size() ? low.peek() : (low.peek() + (long) high.peek()) / 2.0;
}
}Verdict: The standard design.