【面试题41】数据流中的中位数

在这里插入图片描述
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

考点

  • 考查对时间复杂度的分析能力;
  • 考查对数据结构的理解程度。只有对各个常用数据容器的特点非常了解,知道它们的优缺点及适用场景,才能找出最优的解法。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章