⭐算法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 is3
. - For example, for
arr = [2,3]
, the median is(2 + 3) / 2 = 2.5
.
Implement the MedianFinde
r class:
MedianFinder()
initializes theMedianFinder
object.void addNum(int num)
adds the integernum
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
操作:
- 如果最大堆比最小堆多一个元素,返回最大堆的堆顶
- 否则返回两个堆顶的平均值
解决代码
#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),只需要访问堆顶元素
这种方法巧妙地利用了两个堆的性质,使得我们可以在对数时间内添加元素,常数时间内找到中位数。