Q:
A:
用两个堆(一大顶堆、一小顶堆模拟中位数),没见过类似的题目记录一下。
class MedianFinder {
public:
priority_queue<int,vector<int>,less<int>> heap1; //大顶堆
priority_queue<int,vector<int>,greater<int>> heap2; //小顶堆
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if (not heap1.empty() and heap1.top()<num){
heap2.push(num);
}
else{
heap1.push(num);
}
if (heap1.size()<heap2.size()){
heap1.push(heap2.top());
heap2.pop();
}
else if (heap1.size()-heap2.size()>1){
heap2.push(heap1.top());
heap1.pop();
}
}
double findMedian() {
if (heap1.size()>heap2.size()){
return heap1.top();
}
else{
return (heap1.top()+heap2.top())/2.0;
}
}
};