from heapq import *
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.a=[]#小根堆
self.b=[]
def addNum(self, num: int) -> None:
if len(self.a)==len(self.b):
heappush(self.b,-num)
heappush(self.a,-heappop(self.b))
else:
heappush(self.a,num)
heappush(self.b,-heappop(self.a))
def findMedian(self) -> float:
if len(self.a)==len(self.b): return (heappop(self.a)-heappop(self.b))/2
else: return heappop(self.a)
剑指 Offer 41. 数据流中的中位数语法题
最新推荐文章于 2021-03-13 22:49:34 发布