描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
数据范围:数据流中数个数满足1≤n≤1000 ,大小满足 \1≤val≤1000
进阶: 空间复杂度O(n) , 时间复杂度O(nlogn)
我的代码:
采用一个大根堆和一个小根堆来实现,大根堆存放较小的一半元素,小根堆存放较大的一般元素。
这里用了priority_queue与queue的区别是,前者可以定义压出的优先级。
class Solution {
public:
priority_queue<int> max_heap;//最大栈,按照从大到小
priority_queue<int, vector<int>, greater<int>> min_heap;//最小栈,按照从小到大排序
void Insert(int num) {
if(max_heap.empty() || max_heap.top()>num) max_heap.push(num);
else min_heap.push(num);
int a=max_heap.size(), b=min_heap.size();
if(a-b>1){
int cur = max_heap.top();
max_heap.pop();
min_heap.push(cur);
}
else if(b>a){
int cur = min_heap.top();
min_heap.pop();
max_heap.push(cur);
}
}
double GetMedian() {
//double re;
if(max_heap.size() == min_heap.size()){//偶数个数据
return (max_heap.top()+min_heap.top())/2.0;
}
return (double)max_heap.top();
}
};