题目链接:https://leetcode-cn.com/problems/find-median-from-data-stream/
题目如下:
class MedianFinder {
public:
MedianFinder() {
}
void addNum(int num) {
//目的:大根堆中的内容为较小的数,存放的数用于等于或大于小根堆中的数
if(maxheap.size()==0||num<=maxheap.top()) maxheap.push(num);
else minheap.push(num);
//如果大根堆中的数值<小顶堆中的数值,则将小根堆中的数移出,放入大根堆中
while(maxheap.size()<minheap.size()){
int e=minheap.top();
minheap.pop();
maxheap.push(e);
}
//大顶堆最多只能超过小顶堆一个元素,否则,需要移动
while(minheap.size()<maxheap.size()-1){
int e=maxheap.top();
maxheap.pop();
minheap.push(e);
}
}
double findMedian() {
if(maxheap.size()>minheap.size()) return maxheap.top();
else return (maxheap.top()+minheap.top())/2.0;
}
private:
struct Cmp{
bool operator()(const int& a,const int& b){
return a>b;//小根堆
}
};
priority_queue<int,vector<int>,Cmp> minheap;//用于求top K
priority_queue<int> maxheap;//用于求min K
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/