# -*- coding:utf-8 -*- class Solution: def __init__(self) -> None: self.small_heap = [] self.large_heap = [] def Insert(self, num): # write code here import heapq if len(self.small_heap) < len(self.large_heap): # 先将num加入到large中 heapq.heappush(self.large_heap, num) # 将large中的最小值取出,加入到small中 heapq.heappush(self.small_heap, -heapq.heappop(self.large_heap)) else: # 先将num加入到small中 heapq.heappush(self.small_heap, -num) # 将small中的最大值加入到large中 heapq.heappush(self.large_heap, -heapq.heappop(self.small_heap)) def GetMedian(self): if len(self.small_heap) == len(self.large_heap): # 返回小根堆的最大值和大根堆的最小值的平均数 return (-self.small_heap[0] + self.large_heap[0]) / 2 else: # 返回large中最小值 return self.large_heap[0]