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

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

相关推荐
灵感__idea3 小时前
Hello 算法:贪心的世界
前端·javascript·算法
澈2074 小时前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
A.A呐4 小时前
【C++第二十九章】IO流
开发语言·c++
ambition202424 小时前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
cmpxr_4 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法
qiqsevenqiqiqiqi4 小时前
前缀和差分
算法·图论
代码旅人ing5 小时前
链表算法刷题指南
数据结构·算法·链表
kebeiovo5 小时前
atomic原子操作实现无锁队列
服务器·c++
Yungoal5 小时前
常见 时间复杂度计算
c++·算法
6Hzlia5 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵