Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4]
, the median is 3
[2,3]
, the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
For example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
设计题,添加数,找出中位数。
维护两个堆,一个保存较小的半个部分,一个保存较大的半个部分,中位数存在的时候,就取较大的半边的顶部元素,不存在的时候,去两边顶部的均值。
class MedianFinder {
public:
priority_queue<int, vector<int>, less<int> > minn;
priority_queue<int, vector<int>, greater<int> >maxx;
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if(minn.size() > maxx.size())
{
if(num >= minn.top()) maxx.push(num);
else
{
minn.push(num);
maxx.push(minn.top());
minn.pop();
}
}
else
{
if(minn.empty())
{
minn.push(num);
return ;
}
if(num >= minn.top())
{
maxx.push(num);
minn.push(maxx.top());
maxx.pop();
}
else minn.push(num);
}
}
double findMedian() {
if((minn.size() + maxx.size()) & 1) return minn.top();
return (1.0 * minn.top() + maxx.top()) / 2;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
扫码关注腾讯云开发者
领取腾讯云代金券
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. 腾讯云 版权所有