⭐算法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),只需要访问堆顶元素

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

相关推荐
Navigator_Z1 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
JosieBook2 小时前
【鸿蒙开源】把 Windows 任务栏上的流量表搬到鸿蒙 PC:TrafficMonitor 1.86 的 C++ 内核移植实践
c++·windows·harmonyos
电科_银尘2 小时前
【大模型算法与工程 39】PPO:策略比率、裁剪目标与训练稳定性
人工智能·算法·机器学习
shehuiyuelaiyuehao3 小时前
算法68,字符串相乘
算法
Huangjin007_3 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
敲上瘾5 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
驭渊的小故事5 小时前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
炸膛坦客5 小时前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机
小飞在努力6 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
ShineWinsu6 小时前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog