【剑指offer】面试题41:数据流中的中位数——大、小堆实现

在这里插入图片描述

方法一:排序取中位数(超时)

class MedianFinder {
public:
    /** initialize your data structure here. */
    vector<int> record;
    MedianFinder() {

    }
    
    void addNum(int num) {
        record.push_back(num);
    }
    
    double findMedian() {
        double result = 0;
        if( record.size() == 0 )
            return result;
        sort( record.begin(), record.end() );
        //奇数
        if( record.size() & 1 )
        {
            result = record[ record.size() / 2 ];
        }
        else
        {
            result = (double)( record[ record.size() / 2 - 1 ] + record[ record.size() / 2 ] ) / 2;
        }

        return result;
    }
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */

方法二:大、小堆实现

1.通过两个堆,一个最大堆一个最小堆,大小不超过1 ,如果超过1就把大小堆平衡一下
2.中位数如果是奇数则为最大堆的top或最小堆的top,如果最大堆和最小堆的大小相等,则取两个堆顶的平均值
3.最小堆里面的数据都要比最大堆大

class MedianFinder {
public:
    /** initialize your data structure here. */

    //最大堆
    priority_queue< int, vector<int> > max_heap;
    //最小堆
    priority_queue< int, vector<int>, greater<int> > min_heap;
    MedianFinder() {

    }
    
    void addNum(int num) {

        
        if( max_heap.empty() || num < max_heap.top() )
        {
            max_heap.push( num );
        }
        else
            min_heap.push( num );

        //维持堆得大小
        if( max_heap.size() == min_heap.size() + 2)
        {
            min_heap.push(max_heap.top());
            max_heap.pop();
        }
        else if( min_heap.size() == max_heap.size() + 2)
        {
            max_heap.push( min_heap.top() );
            min_heap.pop();
        }

    }
    
    double findMedian() {

        if( ( max_heap.size() + min_heap.size() ) == 0 )
            return -1;
        if( max_heap.size() > min_heap.size() )
        {
            return max_heap.top();
        }
        else if( max_heap.size() < min_heap.size() )
        {
            return min_heap.top();
        }
        else
            return double( max_heap.top() + min_heap.top() ) / 2;

    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值