Find Median from Data Stream

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

For example,
[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

 

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

 

Follow up:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

Solution:

class MedianFinder {
    // [1]
    // [2]
    private PriorityQueue<Integer> left;
    private PriorityQueue<Integer> right;
    /** initialize your data structure here. */
    public MedianFinder() {
        left = new PriorityQueue<>(Collections.reverseOrder());
        right = new PriorityQueue<>();
    }
    
    public void addNum(int num) {
        if (left.isEmpty()) {
            left.offer(num);
        } else {
            int leftMax = left.peek();
            if (num <= leftMax) {
                if (left.size() > right.size()) {
                    left.poll();
                    left.offer(num);
                    right.offer(leftMax);
                } else {
                    left.offer(num);
                }
            } else { 
                if (left.size() > right.size()) {
                    right.offer(num);
                } else {
                    int rightMax = right.poll();
                    if (num < rightMax) {
                        left.offer(num);
                        right.offer(rightMax);
                    } else {
                        left.offer(rightMax);
                        right.offer(num);
                    }
                }
            }
        }
    //     System.out.println("left: " + left);
    //     System.out.println("right: " + right);
    }
    
    public double findMedian() {
        if ((left.size() + right.size()) % 2 == 1) {
            return (double) left.peek();
        } else {
            return (left.peek() + right.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();
 */