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()
相关推荐
C雨后彩虹9 分钟前
任务总执行时长
java·数据结构·算法·华为·面试
风筝在晴天搁浅12 分钟前
代码随想录 463.岛屿的周长
算法
一个不知名程序员www33 分钟前
算法学习入门---priority_queue(C++)
c++·算法
TL滕1 小时前
从0开始学算法——第十八天(分治算法)
笔记·学习·算法
LYFlied1 小时前
【每日算法】LeetCode 84. 柱状图中最大的矩形
前端·算法·leetcode·面试·职场和发展
CoderCodingNo2 小时前
【GESP】C++三级真题 luogu-B4414 [GESP202509 三级] 日历制作
开发语言·c++·算法
Liangwei Lin2 小时前
洛谷 P1955 [NOI2015] 程序自动分析
算法
zwjapple2 小时前
全栈开发面试高频算法题
算法·面试·职场和发展
不穿格子的程序员2 小时前
从零开始写算法——链表篇5:K个一组翻转链表 + 排序链表
算法·链表·分治
青鸟2182 小时前
从资深开发到脱产管理的心态转变
后端·算法·程序员