题目描述
问题分析
使用大小堆来完成: 我们让最大堆总是大于最小堆一个量或者等于最小堆数量,中位数只可能是最大堆顶或最大堆与最小堆堆顶平均值。
c++代码
class MedianFinder {
public:
priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int> maxHeap;
MedianFinder() {
}
void addNum(int num) {
if (maxHeap.empty()) {
maxHeap.push(num);
return;
}
if (num <= maxHeap.top()) maxHeap.push(num);
else minHeap.push(num);
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.push(maxHeap.top());
maxHeap.pop();
}
if (maxHeap.size() < minHeap.size()) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
double findMedian() {
if (maxHeap.size() == minHeap.size() + 1) {
return maxHeap.top();
}
else {
return (maxHeap.top() + minHeap.top()) * 0.5;
}
}
};
|