295. Find Median from Data Stream

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

My Solutions:

用PriorityQueue 和heap的思想, PirorityQueue 会把数从小到大排列,peek时看顶端最小的数

有一个minQ保存所有小于median的数字,maxQ保存所有大于等于median的数字

新数先加进maxQ里,再拿出,变成相反数加进minQ里。如果maxQ比minQ少,再拿出变成相反数加回maxQ里。保证中间数在maxQ的顶端,或者如果是偶数个数,中间数是maxQ和minQ顶端数的中间值

e.g.

add(1), minQ:[], maxQ[1]

add(2), minQ:[1], maxQ[2]

add(3), minQ:[1], maxQ[2,3]

add(4), minQ:[1,2], maxQ[3,4]

class MedianFinder {

    private Queue<Integer> minQ = new PriorityQueue<>();
    private Queue<Integer> maxQ = new PriorityQueue<>();
    
    /** initialize your data structure here. */
    public MedianFinder() {
        
    }
    
    public void addNum(int num) {
        maxQ.add(num);
        minQ.add(-maxQ.poll());
        if (maxQ.size() < minQ.size()) maxQ.add(-minQ.poll());
    }
    
    public double findMedian() {
        return maxQ.size() > minQ.size() ? maxQ.peek() : (maxQ.peek() - minQ.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();
 */

Last updated