703-Kth Largest Element in a Stream
题目:返回数据流中的第K大元素
class KthLargest(object): def __init__(self,k): self.min_heap = [] self.k = k def add(self,data): if len(self.min_heap)<self.k: heapq.heappush(self.min_heap,data) else: heapq.heappushpop(self.min_heap,data) def get_kth(self): return heapq.nsmallest(1,self.min_heap)[0]
注:
构建一个小顶堆,大小为k,每次往里压入数据,第k大元素即为堆顶元素