當(dāng)前位置:
首頁 >
76. Leetcode 295. 数据流的中位数 (堆-技巧一-固定堆)
發(fā)布時(shí)間:2025/4/5
27
豆豆
生活随笔
收集整理的這篇文章主要介紹了
76. Leetcode 295. 数据流的中位数 (堆-技巧一-固定堆)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
技巧一 - 固定堆這個(gè)技巧指的是固定堆的大小 k 不變,代碼上可通過每 pop 出去一個(gè)就 push 進(jìn)來一個(gè)來實(shí)現(xiàn)。而由于初始堆可能是0,我們剛開始需要一個(gè)一個(gè) push 進(jìn)堆以達(dá)到堆的大小為k,因此嚴(yán)格來說應(yīng)該是維持堆的大小不大于k。
?
?
具體可以進(jìn)行如下操作:情況 1: 當(dāng)兩個(gè)堆的元素個(gè)數(shù)之和為偶數(shù)(例如一開始的時(shí)候),為了讓最大堆中多 1 個(gè)元素, 采用這樣的流程:「最大堆 → 最小堆 → 最大堆」;情況 2: 當(dāng)兩個(gè)堆的元素個(gè)數(shù)之和為奇數(shù),此時(shí)最小堆必須多 1個(gè)元素,這樣最大堆和最小堆的元素個(gè)數(shù)才相等, 采用這樣的流程:「最大堆 → 最小堆」 即可。import heapqclass MedianFinder:def __init__(self):self.count = 0self.max_heap = []self.min_heap = []def addNum(self, num: int) -> None:self.count += 1heapq.heappush(self.max_heap, (-num, num))_, max_heap_top = heapq.heappop(self.max_heap)heapq.heappush(self.min_heap, max_heap_top)if self.count & 1:min_heap_top = heapq.heappop(self.min_heap)heapq.heappush(self.max_heap, (-min_heap_top, min_heap_top))def findMedian(self) -> float:if self.count & 1:return self.max_heap[0][1]else:return (self.min_heap[0] + self.max_heap[0][1])/2# Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()總結(jié)
以上是生活随笔為你收集整理的76. Leetcode 295. 数据流的中位数 (堆-技巧一-固定堆)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 74. Leetcode 501. 二叉
- 下一篇: 77. Leetcode 1439. 有