xinyu04

导航

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.

  • 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();
 */

posted on 2022-08-18 02:33  Blackzxy  阅读(4)  评论(0编辑  收藏  举报