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()
相关推荐
leoufung8 分钟前
题目介绍:LeetCode 79. Word Search
leetcode·word·深度优先
小O的算法实验室9 分钟前
2023年IEEE TIV,GA-LNS算法+直升机救援调度,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
foundbug99914 分钟前
Delta并联机器人正逆解实现
算法·机器人
职业码农NO.125 分钟前
《算法与数据结构》:最短路径
数据结构·算法
Ayanami_Reii27 分钟前
进阶数据结构Splay应用-维护数列
数据结构·算法·splay·fhq
是小胡嘛34 分钟前
仿Muduo高并发服务器之Buffer模块
开发语言·c++·算法
琢磨先生David34 分钟前
Java算法题:移除数组中的重复项
java·数据结构·算法
im_AMBER38 分钟前
Leetcode 75 数对和 | 存在重复元素 II
c++·笔记·学习·算法·leetcode
九河云42 分钟前
直播电商数字化:用户行为 AI 分析与选品推荐算法平台建设
人工智能·物联网·算法·推荐算法
CoovallyAIHub43 分钟前
深大团队UNeMo框架:让机器人学会“预判”,效率提升40%
深度学习·算法·计算机视觉