題目描述
如何得到一個數據流中的中位數?如果從數據流中讀出奇數個數值,那麼中位數就是所有數值排序之後位於中間的數值。如果從數據流中讀出偶數個數值,那麼中位數就是所有數值排序之後中間兩個數的平均值。我們使用Insert()方法讀取數據流,使用GetMedian()方法獲取當前讀取數據的中位數。
拒絕一切花裏胡哨,python真香,哈哈哈。直接上代碼,c的有興趣可以看下。
python
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.l = []
def Insert(self, num):
# write code here
self.l.append(num)
self.l.sort()
def GetMedian(self,l):
# write code here
n = len(self.l)
if n%2==1:
return self.l[n//2]
else:
return (self.l[n//2-1]+self.l[n//2])/2.0
c++
class Solution {
private:
vector<int> min;
vector<int> max;
public:
void Insert(int num)
{
int size=min.size()+max.size();
if((size&1)==0)
{
if(max.size()>0 && num<max[0])
{
max.push_back(num);
push_heap(max.begin(),max.end(),less<int>());
num=max[0];
pop_heap(max.begin(),max.end(),less<int>());
max.pop_back();
}
min.push_back(num);
push_heap(min.begin(),min.end(),greater<int>());
}
else
{
if(min.size()>0 && num>min[0])
{
min.push_back(num);
push_heap(min.begin(),min.end(),greater<int>());
num=min[0];
pop_heap(min.begin(),min.end(),greater<int>());
min.pop_back();
}
max.push_back(num);
push_heap(max.begin(),max.end(),less<int>());
}
}
double GetMedian()
{
int size=min.size()+max.size();
if(size<=0)
return 0;
if((size&1)==0)
return (max[0]+min[0])/2.0;
else
return min[0];
}
};