阅读背景:

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,x)
            self.k+=1
        else:
            heapq.heappush(self.min_heap,data)
            self.k += 1
    def get_median(self):
        if self.k%2:
            return heapq.nlargest(1,self.max_heap)[0]
        else:
            return (heapq.nlargest(1,self.max_heap)[0] + heapq.nsmallest(1,self.min_heap)[0])/2
import heapq
class GetMedia



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: