The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

Implement the MedianFinder class:


Test Cases

Example 1:

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

Solution

class MedianFinder {
    PriorityQueue<Integer> first;
    PriorityQueue<Integer> second;
    public MedianFinder() {
        first = new PriorityQueue<>((a,b) -> b-a);
        second = new PriorityQueue<>();
    }

    public void addNum(int num) {
        first.offer(num);
        second.offer(first.poll());
        if (second.size() > first.size()) first.offer(second.poll());
    }

    public double findMedian() {
        if (first.size() > second.size()) return first.peek();
        return (first.peek() + second.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();
 */
Time Complexity: O(1)
Space Complexity: O(1)