大多是 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 | class MedianFinder: |
LeetCode
295. Find Median from Data Stream
480. Sliding Window Median
502. IPO
436. Find Right Interval