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()
相关推荐
驭渊的小故事18 分钟前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
.YM.Z22 分钟前
优选算法——【双指针算法2】C++实现
开发语言·c++·算法
文丑颜不良啊29 分钟前
LeetCode1501~1520题目解析
java·leetcode
zwc32104320551 小时前
第四周第五天——重构成类
c++·人工智能·opencv·算法·计算机视觉
Navigator_Z2 小时前
LeetCode //C - 1311. Get Watched Videos by Your Friends
c语言·算法·leetcode
云析赢指标公式网42 小时前
通达信ATAN均线角度公式源码笔记:四周期角度计算与DRAWBAND色带实现
笔记·算法
21岁被迫秃头2 小时前
SVT-AV1 Mini-Gop决策算法详解+源码分析.md
算法·av1·svt-av1·源码详解·mini-gop决策
Kobebryant-Manba2 小时前
IEKT向量矩阵流程&评估
人工智能·算法·矩阵
Js.Tx2 小时前
【具体数学 Concrete Mathematics】2.1.7 无限和式
算法·具体数学
FPGA信号处理3 小时前
【 凸优化】第六讲:求解器与支持向量机
算法·机器学习·支持向量机