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;
};
全部评论

相关推荐

认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:11
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务