如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
class Solution {
private:
int count = 0;
priority_queue<int, vector<int>, greater<>> minHeap;
priority_queue<int, vector<int>, less<>> maxHeap;
public:
void Insert(int num) {
if(count & 1) {
minHeap.push(num);
auto temp = minHeap.top();
minHeap.pop();
maxHeap.push(temp);
} else {
maxHeap.push(num);
auto temp = maxHeap.top();
maxHeap.pop();
minHeap.push(temp);
}
count++;
}
double GetMedian() {
if(count & 1) {
return minHeap.top();
} else {
return (minHeap.top() + maxHeap.top()) / 2.0;
}
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有