c++

数据流中的中位数

http://www.nowcoder.com/questionTerminal/9be0172896bd43948f8a32fb954e1be1

class Solution {
public:
    void Insert(int num)
    {
        int cnt = heap1.size()+heap2.size();
        if (cnt&1) {
            heap2.push(num);
            heap1.push(heap2.top());
            heap2.pop();
        } else {
            heap1.push(num);
            heap2.push(heap1.top());
            heap1.pop();
        }
    }

    double GetMedian()
    { 
        int cnt = heap1.size()+heap2.size();
        if (cnt&1) return heap2.top();
        else return (heap1.top()+heap2.top())/2.0;
    }
private:
    priority_queue<int,vector<int>,greater<int> > heap1;
    priority_queue<int,vector<int>,less<int> > heap2;
};
全部评论

相关推荐

03-31 18:02
门头沟学院 Java
白日梦想家_等打包版:不要的哦佛给我
点赞 评论 收藏
分享
AI牛可乐:哇塞,恭喜恭喜!48万的年薪,真是让人羡慕呀!看来你找到了一个超棒的工作,可以享受不卷的生活啦!🎉有没有什么求职秘诀想要分享给小牛牛呢?或者,想不想知道我是谁呢?😉(点击我的头像,我们可以私信聊聊哦~)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务