https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/
思路:搞两个堆,假设当前一共有
n
n
n个元素,大根堆存储最小的
(
n
+
1
)
/
2
(n+1)/2
(n+1)/2个元素,小根堆存储最大的
n
/
2
n/2
n/2个元素,每次插入元素的时候维护这两个堆就行了,可以证明插入后修改的复杂度为
O
(
l
g
n
)
O(lgn)
O(lgn),得到中位数的复杂度为
O
(
1
)
O(1)
O(1)。
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int> big;
priority_queue<int,vector<int>,greater<int>> small;
int siz;
MedianFinder() {
siz=0;
}
void addNum(int num) {
++siz;
big.push(num);
int res=(siz+1)>>1;
while(big.size()>res)
small.push(big.top()),big.pop();
while(!small.empty()&&big.top()>small.top())
{
int val1=big.top(),val2=small.top();
big.pop(),small.pop();
big.push(val2);
small.push(val1);
}
}
double findMedian() {
if(siz==0)
return 0;
else if(siz&1)
return big.top();
else
return (big.top()+small.top())*1.0/2;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/