剑指 Offer 41. 数据流中的中位数语法题

tech2024-06-22  70

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)
最新回复(0)