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 小时前
G1 新生代对象晋升老年代:实现机制与 GC 日志
java·jvm·算法
万法若空6 小时前
排列组合恒等式
c++·算法
Nil2086 小时前
leetcode 105从前序和中序遍历序列构造二叉树
算法·leetcode·职场和发展
一直C6 小时前
【数据结构】哈希表+算法复杂度与经典排序查找(C语言)
java·linux·开发语言·数据结构·算法·ubuntu·散列表
淡海水6 小时前
04-02-哈希-Dictionary-TKey-TValue-上-核心数据结构
数据结构·算法·c#·哈希算法·编译·字典·dictionary
戴西软件6 小时前
国内有哪些数据轻量化格式转换软件?
数据库·算法·安全·信息可视化·自动化·rpa
老洋葱Mr_Onion7 小时前
【C++】CSP-J初赛模拟卷七错题整理(作者自用)
c++·算法·深度优先
Nil2087 小时前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
土星云SaturnCloud7 小时前
Real-ESRGAN超分辨率算法原理与边缘侧部署实践
服务器·算法·ai·边缘计算·real-esrgan
cz07107 小时前
hot100_搜索二维矩阵 II
算法·leetcode