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

数据结构: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()

你可能感兴趣的:(力扣算法题目记录,leetcode,python,算法,数据结构)