Two Heaps

大多是 max_heap 和 min_heap 的配合使用。在用索引获取堆顶元素时,注意保证 heap 非空。

In many problems, where we are given a set of elements such that we can divide them into two parts. To solve the problem, we are interested in knowing the largest element in one part and the smallest element in the other part. This pattern is an efficient approach to solve such problems.

This pattern uses Two Heaps to solve these problems; A max heap to find the largest element and a min heap to find the smallest element.

Snippets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class MedianFinder:
def __init__(self):
self.max_heap = []
self.min_heap = []

def add_num(self, num: int) -> None:
if not self.max_heap or num <= -self.max_heap[0]:
heappush(self.max_heap, -num)
else:
heappush(self.min_heap, num)

# rebalance
if len(self.max_heap) > len(self.min_heap) + 1:
heappush(self.min_heap, -heappop(self.max_heap))
if len(self.min_heap) > len(self.max_heap):
heappush(self.max_heap, -heappop(self.min_heap))

def find_median(self) -> float:
if len(self.max_heap) == len(self.min_heap):
return (-self.max_heap[0] + self.min_heap[0]) / 2

return -self.max_heap[0]

LeetCode

295. Find Median from Data Stream
480. Sliding Window Median
502. IPO
436. Find Right Interval