Find Median from Data Stream

LeetCode #295


Description:

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.

Example:

Examples: 
[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.
For example:

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

Idea:

max_heap存小的一半,min_heap存大的一半,保持两个size相同,或者max_heap比min_heap多一个。

如果俩个size相同,则median就是两个top的平均,不同就是max_heap的top。

Time: AddNum O(logn), findMedian O(1).

Code:

class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() {

    }

    void addNum(int num) {
        if(max_heap.empty()){
            max_heap.push(num);
            return;
        }

        if(num<=max_heap.top()){
            max_heap.push(num);
        }
        else{
            min_heap.push(num);
        }

// 注意, heap.size() is unsigned int!!!
        if(max_heap.size() > min_heap.size() + 1){
            int val = max_heap.top();
            max_heap.pop();
            min_heap.push(val);
        }
        else if(min_heap.size() > max_heap.size()){
            int val = min_heap.top();
            min_heap.pop();
            max_heap.push(val);            
        }

    }

    double findMedian() {
        if(max_heap.size()==min_heap.size()){
            return (max_heap.top() + min_heap.top())/2.0;
        }
        else
            return max_heap.top();

    }
private:
    priority_queue<int> max_heap;
    priority_queue<int, vector<int>, greater<int> > min_heap;
};

results matching ""

    No results matching ""