[LC] 295. 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:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

Example:

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

class MedianFinder {

    private PriorityQueue<Integer> smallPq;
    private PriorityQueue<Integer> largePq;
    /** initialize your data structure here. */
    public MedianFinder() {
        // smallPq get the max value for peek()
        smallPq = new PriorityQueue<>((a, b) -> (b - a));
        largePq = new PriorityQueue<>();
    }
    
    public void addNum(int num) {
        if (smallPq.isEmpty() || num <= smallPq.peek()) {
            smallPq.offer(num);
        } else {
            largePq.offer(num);
        }
        
        if (smallPq.size() >= largePq.size() + 2) {
            largePq.offer(smallPq.poll());
        } else if (largePq.size() > smallPq.size()) {
            smallPq.offer(largePq.poll());
        }
    }
    
    public double findMedian() {
        if (smallPq.size() == largePq.size()) {
            return (smallPq.peek() + largePq.peek()) / 2.0;
        } else {
            return (double)(smallPq.peek());
        }
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */
原文地址:https://www.cnblogs.com/xuanlu/p/12015397.html