问题
思路
基本思路就是将前半部分元素维护在大根堆当中。
后半部分元素维护在小根堆当中。
但是要注意的是,大根堆和小根堆可以维护各自的有序性。但是,这两个部分的有序性需要在每次插入的时候特别判断以下。
每次,都进行维护。这样就不会出现某一次插入需要弹出很多元素的情形。
代码
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() : size(0) {}
void addNum(int num) {
if( size & 0x1 ) {
if( !max_heap.empty() && num < max_heap.top() ) {
int e = max_heap.top();
max_heap.pop();
min_heap.push(e);
max_heap.push(num);
}
else
min_heap.push(num);
}
else{
if( !min_heap.empty() && num > min_heap.top() ) {
int e = min_heap.top();
min_heap.pop();
max_heap.push(e);
min_heap.push(num);
}
else
max_heap.push(num);
}
++size;
}
double findMedian() {
if( size & 0x1 ) return max_heap.top();
else return ( max_heap.top() + min_heap.top() ) * 1.0 / 2;
}
private:
priority_queue< int, vector<int>, less<int> > max_heap;
priority_queue< int, vector<int>, greater<int> > min_heap;
int size;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/