(力扣记录)295. 数据流的中位数

发布时间:2024年01月18日

数据结构: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.c1 > 1:
            temp = heapq.heappop(self.large)
            heapq.heappush(self.small, -temp)
            self.c2 -= 1
            self.c1 += 1

    def findMedian(self) -> float:
        if self.c1 == self.c2:
            return (-self.small[0] + self.large[0]) / 2
        elif self.c1 < self.c2:
            return self.large[0]
        else:
            return -self.small[0]


# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()

文章来源:https://blog.csdn.net/Wilson_Lin_01/article/details/135639247
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。