面试题41:数据流中的中位数

两个堆,类似于漏斗的形状,输出两个堆顶的值。

class Solution {
public:
    priority_queue<int, vector<int>, greater<int>> min_heap;
    priority_queue<int> max_heap;
    void Insert(int num)
    {
        max_heap.push(num); //都放入大根堆中, 如果大根堆里面的数量比小根堆大2,则把大根堆的放入小根堆
        if(max_heap.size() - min_heap.size() >= 2){
            int t = max_heap.top();
            max_heap.pop();
            min_heap.push(t);
        }
        if(min_heap.size() && max_heap.top() > min_heap.top()){
            int u = max_heap.top(), v = min_heap.top();
            max_heap.pop(), min_heap.pop();
            max_heap.push(v);
            min_heap.push(u);
        }
    }

    double GetMedian()
    { 
        if(max_heap.size()  == min_heap.size()) return (max_heap.top() + min_heap.top()) / 2.0;
        else return max_heap.top();
    }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值