题解 | #数据流中的中位数#
数据流中的中位数
http://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1
public:
//使用两个堆来存储数据,
priority_queue<int> maxheap; //大根堆,默认降序排列,队列头的元素最大
priority_queue<int, vector<int>, greater<int>> minheap; //队头元素最小
void Insert(int num) {
maxheap.push(num);
if(minheap.size() && maxheap.top() > minheap.top()){
int a = maxheap.top(); maxheap.pop();
int b = minheap.top(); minheap.pop();
maxheap.push(b), minheap.push(a);
}
if(maxheap.size()> minheap.size() + 1){
minheap.push(maxheap.top());
maxheap.pop();
}
}
double GetMedian() {
if((maxheap.si***heap.size()) & 1) return maxheap.top();
return (maxheap.top() + minheap.top()) / 2.0;
}
};