Leetcode_295_数据流的中位数_堆

本文介绍了一种利用两个优先队列实现快速查找中位数的经典算法,通过堆的特性优化插入和查询操作,适用于实时数据流中的中位数计算。

经典的堆找中位数

class MedianFinder {
    PriorityQueue<Integer> pq1;
    PriorityQueue<Integer> pq2;

    /** initialize your data structure here. */
    public MedianFinder() {
        pq1 = new PriorityQueue<>((o1, o2) -> o1 - o2);
        pq2 = new PriorityQueue<>((o1, o2) -> o2 - o1);
    }

    public void addNum(int num) {
        if(pq1.isEmpty() || num >= pq1.element()) {
            pq1.offer(num);
        } else {
            pq2.offer(num);
        }
        if(pq1.size() - pq2.size() >= 2) {
            pq2.offer(pq1.poll());
        } else if(pq2.size() - pq1.size() >= 2) {
            pq1.offer(pq2.poll());
        }
    }

    public double findMedian() {
        if(pq1.size() == pq2.size()) {
            return 1.0 * (pq1.element() + pq2.element()) / 2.0;
        }
        if(pq1.size() > pq2.size()) {
            return pq1.element();
        } else {
            return pq2.element();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值