[LeetCode 295]C++实现数据流的中位数(优先队列实现)
中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。
示例:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
来源:力扣(LeetCode 295)
链接:https://leetcode-cn.com/problems/find-median-from-data-stream
方法:利用优先队列
class MedianFinder {
priority_queue<int,vector<int>,less<int>> big_heap; //大顶堆
priority_queue<int,vector<int>,greater<int>> small_heap; //小顶堆
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
big_heap.push(num);
//维持big_heap.top()永远小于small_heap.top()
small_heap.push(big_heap.top());
big_heap.pop();
//维持bigHeap.size()>=smallHeap.size()
while(big_heap.size()<small_heap.size()){
big_heap.push(small_heap.top());
small_heap.pop();
}
}
double findMedian() {
return big_heap.size()>small_heap.size()?(double)big_heap.top():(double)(big_heap.top()+small_heap.top())/2;
}
};
};