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()
相关推荐
朝朝又沐沐6 分钟前
基于算法竞赛的c++编程(18)string类细节问题
开发语言·c++·算法
记得早睡~30 分钟前
leetcode73-矩阵置零
数据结构·leetcode·矩阵
爱coding的橙子1 小时前
每日算法刷题Day27 6.9:leetcode二分答案2道题,用时1h20min
算法·leetcode·职场和发展
GalaxyPokemon1 小时前
LeetCode - 3. 无重复字符的最长子串
算法·哈希算法·散列表
a.3021 小时前
C++ 时间处理指南:深入剖析<ctime>库
数据结构·c++·算法
亮亮爱刷题1 小时前
算法刷题-回溯
算法
Neil今天也要学习2 小时前
永磁同步电机无速度算法--自适应龙贝格观测器
算法
算AI4 小时前
AI辅助编程:常用的7种Prompt模式
人工智能·算法
TY-20254 小时前
机器学习算法_决策树
算法·决策树·机器学习
子豪-中国机器人4 小时前
C++ 信息学奥赛总复习题
java·jvm·算法