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

//STL 优先队列默认大顶堆
class MedianFinder {
public:  
    void addNum(int num) {
        if(large.empty() || large.top() > num){
            large.push(num);
        }else{
            small.push(num);
        }
        
        //平衡
        if(small.size() > large.size()+1){
            large.push(small.top());
            small.pop();
        }
        
        if(small.size()+1 < large.size()){
            small.push(large.top());
            large.pop();
        }
    }
    
    double findMedian() {
        if(small.size() < large.size()){
            return large.top();
        }
        if(small.size() > large.size()){
            return small.top();
        }
        return double(small.top()+large.top())/2.0;
    }

  private:
    //数据结构:大顶堆与小顶堆,各存一半的数据。大顶堆放较小一半的数据,小顶堆放较大一半的数据
        priority_queue<int> large;
        priority_queue<int,vector<int>,std::greater<int>> small;
};

/**
 * 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/wsw-seu/p/13381549.html