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()
相关推荐
烁3471 小时前
每日一题(小白)暴力娱乐篇20
java·开发语言·算法·排序算法·娱乐
写个博客1 小时前
代码随想录算法训练营第十三天
算法
满天星83035771 小时前
文件的操作
数据结构·c++·算法
heyCHEEMS1 小时前
01背包 Java
java·算法·深度优先
雾月556 小时前
LeetCode 941 有效的山脉数组
java·开发语言·数据结构·算法·leetcode·职场和发展
uhakadotcom8 小时前
归因工具:了解国内外顶级产品
算法·面试·github
小羊在奋斗10 小时前
【多源BFS】01 矩阵 / 飞地的数量 / 地图中的最高点 / 地图分析 / 腐烂的苹果
算法·矩阵·宽度优先
WG_1710 小时前
图论:多源最短路
数据结构·c++·算法
一只小透明啊啊啊啊10 小时前
【leetcode 100】贪心Java版本
java·算法·leetcode
白白糖11 小时前
组合与括号生成(回溯)
python·算法·力扣