[NeetCode 150] Find Median in a Data Stream

Find Median in a Data Stream

The median is the middle value in a sorted list of integers. For lists of even length, there is no middle value, so the median is the mean of the two middle values.

For example:

For arr = [1,2,3], the median is 2.

For arr = [1,2], the median is (1 + 2) / 2 = 1.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.

Example 1:

复制代码
Input:
["MedianFinder", "addNum", "1", "findMedian", "addNum", "3" "findMedian", "addNum", "2", "findMedian"]

Output:
[null, null, 1.0, null, 2.0, null, 2.0]

Explanation:

MedianFinder medianFinder = new MedianFinder();

medianFinder.addNum(1); // arr = [1]

medianFinder.findMedian(); // return 1.0

medianFinder.addNum(3); // arr = [1, 3]

medianFinder.findMedian(); // return 2.0

medianFinder.addNum(2); // arr[1, 2, 3]

medianFinder.findMedian(); // return 2.0

Constraints:

复制代码
-100,000 <= num <= 100,000

findMedian will only be called after adding at least one integer to the data structure.

Solution

We can divide this ordered list into 2 parts. Maintain the first half via a max-heap and maintain the second half via a min-heap. If we keep the balance between the size of these two heaps, we can guarantee that the median is always at the top of them.

To do this, we need to adjust the size of heaps after each addNum. As we only add 1 number once, we only need to move at most 1 element from one heap to another.

Code

heapq is a good way to realize heap (or say priority queue).

py 复制代码
class MedianFinder:

    def __init__(self):
        self.first = [(100001, -100001)]
        self.second = [(100001, 100001)]
        

    def addNum(self, num: int) -> None:
        first_max = self.first[0][1]
        second_min = self.second[0][1]
        if num <= first_max:
            heapq.heappush(self.first, (-num, num))
        else:
            heapq.heappush(self.second, (num, num))
        if len(self.first) > len(self.second) + 1:
            temp = heapq.heappop(self.first)
            heapq.heappush(self.second, (-temp[0], temp[1]))
        if len(self.second) > len(self.first):
            temp = heapq.heappop(self.second)
            heapq.heappush(self.first, (-temp[0], temp[1]))
        

    def findMedian(self) -> float:
        if len(self.first) == len(self.second):
            return (self.first[0][1]+self.second[0][1])/2
        else:
            return self.first[0][1]
        
        
相关推荐
北顾笙9807 分钟前
day28-数据结构力扣
数据结构·算法·leetcode
米粒110 分钟前
力扣算法刷题 Day 48(单调栈)
算法·leetcode·职场和发展
我是无敌小恐龙34 分钟前
Java SE 零基础入门Day03 数组核心详解(定义+内存+遍历+算法+实战案例)
java·开发语言·数据结构·人工智能·算法·aigc·动态规划
广州灵眸科技有限公司1 小时前
瑞芯微(EASY EAI)RV1126B rknn-toolkit-lite2使用方法
linux·网络·人工智能·物联网·算法
旖-旎1 小时前
深搜(二叉树剪枝)(3)
数据结构·c++·算法·力扣·剪枝·递归
流年如夢1 小时前
结构体:定义、使用与内存布局
c语言·开发语言·数据结构·c++·算法
『昊纸』℃2 小时前
C语言学习心得集合 篇1
c语言·算法·编程基础·学习心得·实践操作
Chase_______2 小时前
LeetCode 1456:定长子串中元音的最大数目
算法·leetcode
小O的算法实验室2 小时前
2026年IEEE IOTJ,DNA序列启发相似性驱动粒子群算法+无人机与基站部署,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
谭欣辰2 小时前
Floyd算法:动态规划解最短路径
c++·算法·图论