How do you find the k-th largest element using a heap?
LeetCode Patterns Flashcards: Heap and Priority Queue, Top K, Merge K Sorted
Аудио-карточка · 0:28Nortren·
How do you find the k-th largest element using a heap?
0:28
Maintain a min-heap of size k. Iterate through all elements: add each to the heap, and if the heap size exceeds k, remove the minimum. After processing all elements, the heap top is the k-th largest because the heap contains exactly the k largest elements with the smallest of them on top. This runs in O of n log k time and O of k space, which is better than sorting in O of n log n when k is much smaller than n. An alternative is the quickselect algorithm with O of n average time but O of n squared worst case without randomization.
neetcode.io