Python题解
# -*- coding:utf-8 -*-
import heapq
class Solution:
def __init__(self):
self.max_ = []
self.min_ = []
def Insert(self, num):
if (len(self.max_) + len(self.min_)) % 2 == 1: # 奇数
if len(self.max_)>0 and -self.max_[0] > num:
heapq.heappush(self.min_, -self.max_[0])
heapq.heapreplace(self.max_, -num)
else:
heapq.heappush(self.min_, num)
else: # 偶数
if len(self.min_)>0 and self.min_[0] < num:
heapq.heappush(self.max_, -self.min_[0])
heapq.heapreplace(self.min_, num)
else:
heapq.heappush(self.max_, -num)
def GetMedian(self, x):
if (len(self.max_) + len(self.min_)) % 2 == 1:
return -self.max_[0]
else:
return float(-self.max_[0] + self.min_[0]) / 2
考点
- 考查对时间复杂度的分析能力;
- 考查对数据结构的理解程度。只有对各个常用数据容器的特点非常了解,知道它们的优缺点及适用场景,才能找出最优的解法。