力扣- 剑指 Offer 41题 数据流中的中位数(C++)- 大顶堆、小顶堆

题目链接:https://leetcode.cn/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/
题目如下:
在这里插入图片描述

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

    }
    
    void addNum(int num) {
        //目的:minheap中放较大的元素,堆顶为最小的元素;maxheap中放较小的元素,堆顶为最大的元素
        //如果是奇数:大顶堆元素数-小顶堆元素数=1
        //如果是偶数:大顶堆元素数=小顶堆元素数
        if(maxheap.size()==0||num<maxheap.top()) maxheap.push(num);
        else minheap.push(num);

        while(maxheap.size()<minheap.size()){//小顶堆元素放到大顶堆
            int temp=minheap.top();
            minheap.pop();
            maxheap.push(temp);
        }

        while(minheap.size()<maxheap.size()-1){//大顶堆元素放到小顶堆
            int temp=maxheap.top();
            maxheap.pop();
            minheap.push(temp);
        }
    }
    
    double findMedian() {
        if(maxheap.size()>minheap.size()) return maxheap.top();
        else return (maxheap.top()+minheap.top())/2.0;
    }
private:
    priority_queue<int> maxheap;//放较小的元素
    priority_queue<int,vector<int>,greater<int>> minheap;//放较大的元素
};

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

余额充值