思路:
对顶堆数据结构,up是小根堆,down是大根堆,维持数组数据向上是递增的。且down的元素与up的元素相等或者大于1。
对于要插入的元素,如果down是空的,或者当前元素小于down中最大的数,则插入到down中。
如果元素个数是奇数个则答案是down的top,否则是(down.top() + up.top() ) / 2.0。
代码:
class MedianFinder {
public:
MedianFinder() {
}
void addNum(int num) {
flag = !flag;
if(down.empty() || num <= down.top()){
down.push(num);
if(down.size() > up.size() + 1){
up.push(down.top());
down.pop();
}
}
else{
up.push(num);
if(up.size() > down.size()){
down.push(up.top());
up.pop();
}
}
}
double findMedian() {
if(flag) return down.top();
return (down.top() + up.top() ) / 2.0;
}
priority_queue<int,vector<int>,greater<int>> up;
priority_queue<int,vector<int>,less<int>> down;
bool flag = false;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
评论区