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()
相关推荐
地平线开发者1 天前
征程 6 | 灰度图部署链路介绍
算法·自动驾驶
地平线开发者1 天前
手撕大模型|KVCache 原理及代码解析
算法·自动驾驶
共享家95271 天前
经典动态规划题解
算法·leetcode·动态规划
Pluchon1 天前
硅基计划3.0 Map类&Set类
java·开发语言·数据结构·算法·哈希算法·散列表
☼←安于亥时→❦1 天前
PyTorch之张量创建与运算
人工智能·算法·机器学习
子豪-中国机器人1 天前
枚举算法和排序算法能力测试
开发语言·c++·算法
qiuyunoqy1 天前
基础算法之二分算法 --- 2
算法
1白天的黑夜11 天前
栈-844.比较含退格的字符串-力扣(LeetCode)
c++·leetcode·
爱干饭的boy1 天前
手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】
java·数据结构·后端·算法·spring
二哈不在线1 天前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划