题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
tips:本题在读取数据流的同时给出当前中位数。调用完insert()之后紧接着调用getmedian()。每次读取数据时都要进行中位数判断,我们可以用两个堆实现,一个大根堆存较小的那一半数据,另一个小根堆存较大的一半数据。存数据时先存到大根堆中,若为奇数,return 大根堆首个元素;若为偶数时,return 大根怼和小根堆首元素均值(转化浮点)。那么如何保证较小的一半始终在大根堆?只需要在两个元素开始,各自建立完大小根堆后对首元素进行大小判断,小的元素交换至大根堆首,然后再各自调整为堆结构即可。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.big=[]
self.small=[]
self.count=0
def Insert(self, num):
# write code here
if self.count%2==0:
self.small.append(num)
else:
self.big.append(num)
self.count+=1
def adjust_big_heap(self,arr,start,lenth):#调整为大根堆
root=start
child=root*2+1
while child<lenth:
if child+1<lenth and arr[child+1]>arr[child]:
child+=1
if arr[child]>arr[root]:
arr[child],arr[root]=arr[root],arr[child]
root=child
child=2*root+1
else:
break
def adjust_small_heap(self,arr,start,lenth):#调整为小根堆
root=start
child=root*2+1
while child<lenth:
if child+1<lenth and arr[child+1]<arr[child]:
child+=1
if arr[child]<arr[root]:
arr[child],arr[root]=arr[root],arr[child]
root=child
child=2*root+1
else:
break
def GetMedian(self,x):
# write code here
if self.count==1:
return self.small[0]
for i in range(((len(self.small))-2)>>1,-1,-1):
self.adjust_big_heap(self.small,i,len(self.small))
for i in range(((len(self.big))-2)>>1,-1,-1):
self.adjust_small_heap(self.big,i,len(self.big))
if self.small[0]>self.big[0]:
self.small[0],self.big[0]=self.big[0],self.small[0]
self.adjust_big_heap(self.small,0,len(self.small))
self.adjust_small_heap(self.big,0,len(self.big))
if self.count%2==0:
return (self.small[0]+self.big[0])/2.0
return self.small[0]