- 分析
维护两个堆,一个大根堆,一个小根堆。维护两个状态,大根堆的堆顶元素的值比小根堆的堆顶元素的值小,并且大根堆和小根堆个数差不大于1,这样中位数或是两个堆堆顶的平均值,或是其中一个堆的堆顶元素。这个和两个堆的元素的个数相关。插入元素的时候,维护两个堆状态的方法见代码。这个题是堆中典型的题目!!!!
- 代码
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int> big_heap;
priority_queue<int, vector<int>, greater<int>> small_heap;
MedianFinder() {
}
void addNum(int num) {
int big_heap_size = big_heap.size();
int small_heap_size = small_heap.size();
if(big_heap_size == small_heap_size){//大根堆的个数和小根堆的个数相等的情况
if(!big_heap.empty() && num > big_heap.top()){
small_heap.push(num);
}else{
big_heap.push(num);
}
}else if(big_heap_size < small_heap_size){//大根堆的个数比小根堆少的情况
if(!small_heap.empty() && num > small_heap.top()){
big_heap.push(small_heap.top());
small_heap.pop();
small_heap.push(num);
}else{
big_heap.push(num);
}
}else{//大根堆的个数比小根堆duo的情况
if(!big_heap.empty() && num < big_heap.top()){
small_heap.push(big_heap.top());
big_heap.pop();
big_heap.push(num);
}else{
small_heap.push(num);
}
}
}
double findMedian() {
int big_heap_size = big_heap.size();
int small_heap_size = small_heap.size();
double ans = 0;
if(big_heap_size == small_heap_size){
if(big_heap_size != 0){
ans = (big_heap.top() + small_heap.top()) / 2.0;
}
}else if(big_heap_size > small_heap_size){
ans = big_heap.top();
}else{
ans = small_heap.top();
}
return ans;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/