ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 295 Find Median from Data Stream

2022-08-18 03:00:08  阅读:135  来源: 互联网

标签: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
来源: https://www.cnblogs.com/xinyu04/p/16597414.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有