leetcode-295-Find Median from Data Stream

问题

题目:[leetcode-295]

思路

基本思路就是将前半部分元素维护在大根堆当中。
后半部分元素维护在小根堆当中。

但是要注意的是,大根堆和小根堆可以维护各自的有序性。但是,这两个部分的有序性需要在每次插入的时候特别判断以下。
每次,都进行维护。这样就不会出现某一次插入需要弹出很多元素的情形。

代码

class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() : size(0) {}

    void addNum(int num) {
        if( size & 0x1 ) {
            if( !max_heap.empty() && num < max_heap.top() ) {
                int e = max_heap.top();
                max_heap.pop();

                min_heap.push(e);
                max_heap.push(num);
            }
            else
                min_heap.push(num);
        }
        else{
            if( !min_heap.empty() && num > min_heap.top()  ) {
                int e = min_heap.top();
                min_heap.pop();

                max_heap.push(e);
                min_heap.push(num);
            }
            else
                max_heap.push(num);
        }
        ++size;
    }

    double findMedian() {
        if( size & 0x1 ) return max_heap.top();
        else return ( max_heap.top() + min_heap.top() ) * 1.0 / 2;
    }
private:
    priority_queue< int, vector<int>, less<int> > max_heap;
    priority_queue< int, vector<int>, greater<int> > min_heap;
    int size;
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值