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
考點
- 考查對時間複雜度的分析能力;
- 考查對數據結構的理解程度。只有對各個常用數據容器的特點非常瞭解,知道它們的優缺點及適用場景,才能找出最優的解法。