前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 295. Find Median from Data Stream

Leetcode 295. Find Median from Data Stream

作者头像
triplebee
发布2018-03-27 16:50:39
6570
发布2018-03-27 16:50:39
举报

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:

代码语言:javascript
复制
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

设计题,添加数,找出中位数。

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

代码语言:javascript
复制
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();
 */   
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档