其他分享
首页 > 其他分享> > LeetCode 295 Find Median from Data Stream

LeetCode 295 Find Median from Data Stream

作者:互联网

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

Implement the MedianFinder class:

Solution

我们用一个大根堆和一个小根堆来维护。而基础的优先队列 \(priority\_queue\) 就是大根堆,所以我们利用两个优先队列即可。

具体来说,\(left\) 队列(大根堆)来维护从 \(mid\) 到 \(min\) 的序列,而 \(right\) (小根堆)维护 \(mid+1\) 到 \(max\) 的序列

点击查看代码
class MedianFinder {
private:
    priority_queue<int,vector<int>,greater<int>> right;
    priority_queue<int> left;
public:
    MedianFinder() {
        
    }
    
    void addNum(int num) {
        if(left.size()==0){
            left.push(num);return;
        }
        if(num>left.top()){
            right.push(num);
        }
        else left.push(num);
        if(left.size()>right.size()+1){
            right.push(left.top());
            left.pop();
        }
        else if (right.size()>left.size()){
            left.push(right.top());
            right.pop();
        }
    }
    
    double findMedian() {
        if(left.size()==right.size())
            return (left.top()+right.top())/2.0;
        return left.top();
    }
};

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

标签:right,Stream,top,Median,num,MedianFinder,size,Find,left
来源: https://www.cnblogs.com/xinyu04/p/16597414.html