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()
相关推荐
DoraBigHead3 分钟前
小哆啦解题记——两数失踪事件
前端·算法·面试
不太可爱的大白3 分钟前
Mysql分片:一致性哈希算法
数据库·mysql·算法·哈希算法
Tiandaren4 小时前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说7 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy7 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特9 小时前
每日mysql
数据结构·算法
chao_78910 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
lifallen11 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法