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.

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
解题思路:本题思路比较巧妙,不太容易想到。建立两个堆,两个堆的大小差1,一个是用来求小的部分的最大值,一个是用来求大的部分的最小值,这边比较tricky的就是把val去相反数,这样最大堆就成了最小堆了。
另外maxHeap.push(-minHeap.top());minHeap.pop();把最小部分的最大值放到最大堆里面去也很神奇。
class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() {
        
    }
    
    void addNum(int num) {
        minHeap.push(num);
        maxHeap.push(-minHeap.top());
        minHeap.pop();
        if(minHeap.size() < maxHeap.size()) {
            minHeap.push(-maxHeap.top());
            maxHeap.pop();
        }
    }
    
    double findMedian() {
        return minHeap.size() > maxHeap.size() ? minHeap.top() : (minHeap.top() - maxHeap.top()) / 2.0;
    }
private:
    priority_queue<int>minHeap,maxHeap;
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */

 

posted @ 2017-10-07 20:15  Tsunami_lj  阅读(128)  评论(0编辑  收藏  举报