剑指OFFER41

剑指OFFER41
在这里插入图片描述
在这里插入图片描述
在C++中使用priority_queue类型变量
//升序队列:先弹出的值是最小值,保留最大值在队列中
priority_queue <int,vector,greater > q;
//降序队列:先弹出的值是最大值,保留最小值在队列中,默认为less
priority_queue <int,vector,less >q;
small_heap存储数值较小的数,big_heap存储数值较大的数
addNum函数:
当small_heap为空,优先存储到small_heap
当两变量尺寸大小一样,则将num与small_heap.top()比较,大的话存储到big_heap中,否则存储到small_heap中
当small_heap尺寸较大时,则将num与small_heap.top()比较,大的话存储到big_heap中;否则先将small_heap.top()存储到big_heap中并弹出small_heap.top(),之后再将num存储到small_heap中
当big_heap尺寸较大时,则将num与big_heap.top()比较,小的话直接存储到small_heap中;否则先将big_heap.top()存储到small_heap中,再弹出big_heap.top(),之后再将num存储到big_heap中
findMedian函数:
如果small_heap和big_heap尺寸大小一样,则返回二者堆顶的平均值
否则返回尺寸较大的变量的堆顶值

class MedianFinder {
public:
    priority_queue<int,vector<int>,less<int>> small_heap;
    priority_queue<int,vector<int>,greater<int>> big_heap; 
    /** initialize your data structure here. */
    MedianFinder() {

    }
    
    void addNum(int num) {
        if(small_heap.empty()){
            small_heap.push(num);
            return;
        }
        if(small_heap.size()==big_heap.size()){
            if(num>=small_heap.top()){
                big_heap.push(num);
            }
            else{
                small_heap.push(num);
            }
        }
        else if(small_heap.size() > big_heap.size()){
            if(num >= small_heap.top()){
                big_heap.push(num);
            }
            else{
                big_heap.push(small_heap.top());
                small_heap.pop();
                small_heap.push(num);
            }
        }
        else if(small_heap.size() < big_heap.size()){
            if(num <= big_heap.top()){
                small_heap.push(num);
            }
            else{
                small_heap.push(big_heap.top());
                big_heap.pop();
                big_heap.push(num);
            }
        }
    }
    
    double findMedian() {
        if(small_heap.size() == big_heap.size()){
            return 0.5*(small_heap.top()+big_heap.top());
        }
        return big_heap.size()>small_heap.size()?big_heap.top():small_heap.top();
    }
};

/**
 * 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、付费专栏及课程。

余额充值