数据结构:Heap
时间复杂度:O(1) 获取中位数 ;O(logN) 插入新值
空间复杂度:O(N)
代码实现:
class MedianFinder:
def __init__(self):
self.small = []
self.large = []
self.c1 = 0
self.c2 = 0
heapq.heapify(self.small)
heapq.heapify(self.large)
def addNum(self, num: int) -> None:
# push to lists:
if self.large and num > self.large[0]:
heapq.heappush(self.large, num)
self.c2 += 1
else:
heapq.heappush(self.small, -num)
self.c1 += 1
# switch element between two queue:
if self.c1 - self.c2 > 1:
temp = -heapq.heappop(self.small)
heapq.heappush(self.large, temp)
self.c1 -= 1
self.c2 += 1
if self.c2 - self