⭐算法OJ⭐数据流的中位数【最小堆】Find Median from Data Stream

最小堆

最小堆是一种特殊的完全二叉树数据结构。

基本定义

  • 堆性质:每个节点的值都小于或等于其子节点的值(根节点是最小值)
  • 完全二叉树性质:除了最底层外,其他层的节点都是满的,且最底层的节点都靠左排列

关键特性

  • 根节点最小:堆顶元素始终是堆中的最小值
  • 高效操作:
    • 获取最小值: O ( 1 ) O(1) O(1)
    • 插入元素: O ( l o g n ) O(log n) O(logn)
    • 删除最小值: O ( l o g n ) O(log n) O(logn)

实现方式

最小堆通常用数组实现,利用数组索引表示树结构:

  • 对于索引 i 的元素:
    • 父节点索引:(i-1)/2
    • 左子节点索引:2i+1
    • 右子节点索引:2i+2

问题描述

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 1 0 − 5 10^{-5} 10−5 of the actual answer will be accepted.

Example:

Input

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

Output

复制代码
[null, null, null, 1.5, null, 2.0]

Explanation

复制代码
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

问题描述

设计一个数据结构,能够支持以下两种操作:

  • addNum(int num) - 向数据结构中添加一个整数
  • findMedian() - 返回当前所有元素的中位数

如果元素数量是奇数,中位数是最中间的数;如果是偶数,中位数是中间两个数的平均值。

方法思路

数据结构

我们可以使用两个堆来高效解决这个问题:

  • 一个最大堆max_heap存储较小的一半数字
  • 一个最小堆min_heap存储较大的一半数字

这样设计可以保证:

  • 最大堆的堆顶是较小一半数字中的最大值
  • 最小堆的堆顶是较大一半数字中的最小值
  • 两个堆的大小保持平衡(大小相等或最大堆比最小堆多1)

addNum 操作:

  • 先将新数字加入最大堆
  • 然后将最大堆的堆顶(当前最大值)移到最小堆
  • 最后检查并平衡两个堆的大小,确保最大堆的大小不小于最小堆

findMedian 操作:

  • 如果最大堆比最小堆多一个元素,返回最大堆的堆顶
  • 否则返回两个堆顶的平均值

解决代码

cpp 复制代码
#include <queue>
#include <vector>

using namespace std;

class MedianFinder {
private:
    priority_queue<int> max_heap; // 存储较小的一半,最大堆
    priority_queue<int, vector<int>, greater<int>> min_heap; // 存储较大的一半,最小堆

public:
    MedianFinder() {}
    
    void addNum(int num) {
        // 先将数字加入最大堆
        max_heap.push(num);
        
        // 将最大堆的最大值移到最小堆
        min_heap.push(max_heap.top());
        max_heap.pop();
        
        // 平衡两个堆的大小
        if (max_heap.size() < min_heap.size()) {
            max_heap.push(min_heap.top());
            min_heap.pop();
        }
    }
    
    double findMedian() {
        if (max_heap.size() > min_heap.size()) {
            return max_heap.top();
        } else {
            return (max_heap.top() + min_heap.top()) / 2.0;
        }
    }
};

复杂度分析

  • addNum: O ( l o g n ) O(log n) O(logn),因为堆的插入和删除操作都是对数时间复杂度
  • findMedian: O ( 1 ) O(1) O(1),只需要访问堆顶元素

这种方法巧妙地利用了两个堆的性质,使得我们可以在对数时间内添加元素,常数时间内找到中位数。

相关推荐
vibecoding日记6 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21388 小时前
Verilog参数化游程编码RLE模块
算法
望易8 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络12 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc