Python通过堆寻找数据流中的中位数
数据流中的中位数
http://www.nowcoder.com/questionTerminal/9be0172896bd43948f8a32fb954e1be1
题解中第三种做法的python实现,大顶堆通过取反实现,然后需要注意的是编译器是python2所以要除以2.0,要不然会丢失精度
# -*- coding:utf-8 -*- import heapq class Solution: def __init__(self): self.left = [] self.right = [] def Insert(self, num): # write code here if not self.right: heapq.heappush(self.right, num) elif len(self.left) == len(self.right): left = -self.left[0] if num < left: le = heapq.heappop(self.left) heapq.heappush(self.left, -num) heapq.heappush(self.right, -le) else: heapq.heappush(self.right, num) else: r = self.right[0] if num <= r: heapq.heappush(self.left, -num) else: ri = heapq.heappop(self.right) heapq.heappush(self.left, -ri) heapq.heappush(self.right, num) def GetMedian(self, s): # write code here # print(self.left, self.right) if len(self.left) == len(self.right): return (-self.left[0] + self.right[0]) / 2.0 else: return self.right[0]