295. Find Median from Data Stream

16 阅读1分钟

image.png

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; // min heap
    PriorityQueue<Integer> leftHalf; // max heap
    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); // add to left first and move the biggest left to right
            rightHalf.add(leftHalf.poll());
        } else {
            // Means total count is odd (because A will have 1 more than B)
            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();
        }
    }
}