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

相关推荐

喜欢走神的孤勇者练习时长两年半:爱华,信华,等华,黑华
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务