295. Find Median from Data Stream [Hard] 大顶堆和小顶堆

本文介绍了一种高效算法,用于处理不断变化的数据流并实时计算中位数。该算法利用两个堆数据结构来保持数据流中较小一半和较大一半数值的平衡。通过这种方式,可以在O(log n)时间内插入新元素,并在O(1)时间内查找中位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

17368230-a6f06dd04b26ed90.png
295. Find Median from Data Stream
class MedianFinder(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.low = []
        self.high = []

    def addNum(self, num):
        """
        :type num: int
        :rtype: None
        """
        if len(self.low) == len(self.high):
            if len(self.low) == 0 or num < -self.low[0]:
                heapq.heappush(self.low, -num)
            else:
                heapq.heappush(self.high, num)
        elif len(self.low) > len(self.high):
            if num > -self.low[0]:
                heapq.heappush(self.high, num)
            else:
                temp = -self.low[0]
                heapq.heappop(self.low)
                heapq.heappush(self.low, -num)
                heapq.heappush(self.high, temp)
        else:
            if num > self.high[0]:
                temp = self.high[0]
                heapq.heappop(self.high)
                heapq.heappush(self.low, -temp)
                heapq.heappush(self.high, num)
            else:
                heapq.heappush(self.low, -num)

    def findMedian(self):
        """
        :rtype: float
        """
        if len(self.low) == len(self.high):
            return 0.5 * (self.high[0] - self.low[0])
        elif len(self.low) > len(self.high):
            return -self.low[0]
        else:
            return self.high[0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值