Leetcode 295. Find Median from Data Stream

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012614906/article/details/70238469

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
设计题,添加数,找出中位数。

维护两个堆,一个保存较小的半个部分,一个保存较大的半个部分,中位数存在的时候,就取较大的半边的顶部元素,不存在的时候,去两边顶部的均值。

class MedianFinder {
public:
    priority_queue<int, vector<int>, less<int> > minn;
    priority_queue<int, vector<int>, greater<int> >maxx;
    /** initialize your data structure here. */
    MedianFinder() {
        
    }
    
    void addNum(int num) {
        if(minn.size() > maxx.size())
        {
            if(num >= minn.top()) maxx.push(num);
            else
            {
                minn.push(num);
                maxx.push(minn.top());
                minn.pop();
            }
        }
        else
        {
            if(minn.empty())
            {
                minn.push(num);
                return ;
            }
            if(num >= minn.top())
            {
                
                maxx.push(num);
                minn.push(maxx.top());
                maxx.pop();
            }
            else minn.push(num);
            
        }
        
    }
    
    double findMedian() {
        if((minn.size() + maxx.size()) & 1) return minn.top();
        return (1.0 * minn.top() + maxx.top()) / 2;
    }
};

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


猜你喜欢

转载自blog.csdn.net/u012614906/article/details/70238469
今日推荐