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

LeetCode 295 Find Median from Data Stream

时间:2022-08-18 02:44:11浏览次数:63  
标签:right Stream top Median num MedianFinder size Find left

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.

  • For example, for arr = [2,3,4], the median is 3.
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • double findMedian() returns the median of all elements so far. Answers within \(10^{-5}\) of the actual answer will be accepted.

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
From: https://www.cnblogs.com/xinyu04/p/16597414.html

相关文章