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

相关推荐

12-15 14:16
门头沟学院 Java
回家当保安:发offer的时候会背调学信网,最好不要这样。 “27届 ”和“28届以下 ”公司招聘的预期是不一样的。
实习简历求拷打
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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