41-数据流中的中位数
题目:如何得到一个数据流中的中位数?
import heapq class GetMedian(object): def __init__(self): self.max_heap = [] self.min_heap = [] self.k = 0 def insert(self,data): if self.k%2==0: x = heapq.heappushpop(self.min_heap,data) heapq.heappush(self.max_heap,-1*x) self.k+=1 else: x = heapq.heappushpop(self.max_heap, -1*data) heapq.heappush(self.min_heap,-1*x) self.k += 1 def get_median(self): if self.k%2: return -1*heapq.nsmallest(1,self.max_heap)[0] else: return (-1*heapq.nsmallest(1,self.max_heap)[0] + heapq.nsmallest(1,self.min_heap)[0])/2
注:使用一个大顶堆和一个小顶堆来实现,大顶堆存储左半部分小的数,小顶堆存储右半部分大的数。插入数时,如果数量为偶数,先插入小顶堆,获取堆顶最小值,然后将其插入大顶堆;如果数量为奇数,先插入小顶堆,获取堆顶最大值,然后将其插入小顶堆。本题大顶堆是用小顶堆实现,将元素取相反数之后即可。