[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]
        
        
相关推荐
写代码的橘子n8 分钟前
unordered_set 的常用函数
数据结构·算法·哈希算法
EnigmaCoder19 分钟前
蓝桥杯刷题周计划(第二周)
学习·算法·蓝桥杯
黑金IT23 分钟前
深入理解人脸特征向量及图片转换方法与开发架构
算法·架构
HP-Patience38 分钟前
决策树 vs 神经网络:何时使用?
神经网络·算法·决策树
AI很强39 分钟前
matlab常见的配图代码实现1
开发语言·算法·matlab
飞川00144 分钟前
🚀 力扣热题 78:子集(详细解析)
算法
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧1 小时前
C语言_数据结构总结6:链式栈
c语言·开发语言·数据结构·算法·链表·visualstudio·visual studio
于慨1 小时前
数据结构(王卓版)
数据结构
田梓燊1 小时前
leetcode 95.不同的二叉搜索树 Ⅱ
数据结构·算法·leetcode
IT猿手1 小时前
2025最新群智能优化算法:云漂移优化(Cloud Drift Optimization,CDO)算法求解23个经典函数测试集,MATLAB
开发语言·数据库·算法·数学建模·matlab·机器人