Leetcode 295. Find Median from Data Stream

Problem

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

  • For example, for arr = [2,3,4], the median is 3.
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.

Algorithm

Use two heap to save the data, each save half of the total data.

Code

python3 复制代码
class MedianFinder:

    def __init__(self):
        self.small_heap = []
        self.large_heap = []
        self.heap_size = 0

    def addNum(self, num: int) -> None:
        heapq.heappush(self.small_heap, -num)
        if self.large_heap and (self.large_heap[0] > -self.large_heap[0]):
            heapq.heappush(self.large_heap, -heapq.heappop(self.small_heap))
            heapq.heappush(self.small_heap, -heapq.heappop(self.large_heap))
        if self.heap_size % 2 == 0:
            heapq.heappush(self.large_heap, -heapq.heappop(self.small_heap))
        self.heap_size += 1

    def findMedian(self) -> float:
        if not self.heap_size:
            return None
        if self.heap_size % 2 == 0:
            return (self.large_heap[0] - self.small_heap[0]) / 2
        else: 
            return self.large_heap[0]


# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
相关推荐
小学生的信奥之路5 分钟前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
你知道网上冲浪吗1 小时前
【原创理论】Stochastic Coupled Dyadic System (SCDS):一个用于两性关系动力学建模的随机耦合系统框架
python·算法·数学建模·数值分析
地平线开发者2 小时前
征程 6 | PTQ 精度调优辅助代码,总有你用得上的
算法·自动驾驶
Tisfy3 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
CoovallyAIHub3 小时前
为高空安全上双保险!无人机AI护航,YOLOv5秒判安全带,守护施工生命线
深度学习·算法·计算机视觉
huangzixuan10073 小时前
08.18总结
算法·深度优先·图论
逆向菜鸟4 小时前
【摧毁比特币】椭圆曲线象限细分求k-陈墨仙
python·算法
DolphinDB4 小时前
DolphinDB 回测插件快速上手
算法
利刃大大4 小时前
【动态规划:路径问题】最小路径和 && 地下城游戏
算法·动态规划·cpp·路径问题
武大打工仔4 小时前
用 Java 复现哲学家就餐问题
算法