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()
相关推荐
10001hours1 小时前
初阶数据结构.1.顺序表.通讯录项目(只有源码和注释)
数据结构·算法
Emilia486.2 小时前
八大排序算法
算法·排序算法
blammmp3 小时前
算法专题十九:记忆化搜索(暴搜->记忆化搜索)
算法·深度优先·记忆化搜索
MicroTech20253 小时前
边缘智能的创新:MLGO微算法科技推出基于QoS感知的边缘大模型自适应拆分推理编排技术
科技·算法·ai
王哈哈^_^5 小时前
【数据集】【YOLO】目标检测游泳数据集 4481 张,溺水数据集,YOLO河道、海滩游泳识别算法实战训练教程。
人工智能·算法·yolo·目标检测·计算机视觉·分类·视觉检测
巴里巴气5 小时前
第73题 矩阵置零
线性代数·算法·矩阵
voice6706 小时前
密码学实验二
算法·密码学·哈希算法
Blossom.1187 小时前
把AI“编”进草垫:1KB决策树让宠物垫自己报「如厕记录」
java·人工智能·python·算法·决策树·机器学习·宠物
寂静山林7 小时前
UVa 10989 Bomb Divide and Conquer
算法
兮山与7 小时前
算法23.0
算法