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 小时前
LeetCode 热题 100——子串——和为 K 的子数组
算法·leetcode·职场和发展
zl_vslam2 小时前
SLAM中的非线性优-3D图优化之李群李代数在Opencv-PNP中的应用(四)
人工智能·opencv·算法·计算机视觉
Run_Teenage5 小时前
C++:智能指针的使用及其原理
开发语言·c++·算法
mit6.8246 小时前
二维差分+前缀和
算法
民乐团扒谱机6 小时前
自然的算法:从生物进化到智能优化 —— 遗传算法的诗意与硬核“
算法
希望有朝一日能如愿以偿6 小时前
力扣每日一题:仅含1的子串数
算法·leetcode·职场和发展
漂流瓶jz7 小时前
SourceMap数据生成核心原理:简化字段与Base64VLQ编码
前端·javascript·算法
今天的砖很烫7 小时前
ThreadLocal 中弱引用(WeakReference)设计:为什么要 “故意” 让 Key 被回收?
jvm·算法
苏小瀚7 小时前
算法---FloodFill算法和记忆化搜索算法
数据结构·算法·leetcode
苏小瀚7 小时前
算法---二叉树的深搜和回溯
数据结构·算法