数据流中的中位数
如何得到一个数据流中的中位数?
如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。
如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
算法:维护两个堆
class Solution { public: priority_queue<int>max_heap; priority_queue<int, vector<int>, greater<int>>min_heap; void insert(int num){ max_heap.push(num); if(min_heap.size()&&max_heap.top()>min_heap.top()){ auto x=max_heap.top(),y=min_heap.top(); min_heap.pop(),max_heap.pop(); min_heap.push(x),max_heap.push(y); } if(max_heap.size()>min_heap.size()+1){ min_heap.push(max_heap.top()); max_heap.pop(); } } double getMedian(){ if(max_heap.size()+min_heap.size()&1)return max_heap.top(); return (max_heap.top()+min_heap.top())/2.0; } };