Each subpattern solves a specific type of problem. Click on a card to view its template.
Template for: Top-K Elements
To find the k largest: use a MIN-heap of size k. To find the k smallest: use a MAX-heap of size k.
Push every element into the heap. If size exceeds k, pop the top (worst of the k candidates).
After processing all elements, the heap contains exactly the top-k. For kth largest, the root is the answer.
1// Top-K Largest using a min-heap of size k2// Root = k-th largest; heap contains the k largest seen so far.3int findKthLargest(vector<int>& nums, int k)4{5 // min-heap: smallest of the top-k sits at the root6 priority_queue<int, vector<int>, greater<int>> minHeap;78 for (int x : nums)9 {10 minHeap.push(x);1112 if ((int)minHeap.size() > k)13 {14 minHeap.pop(); // evict the smallest — it's not in top-k15 }16 }1718 return minHeap.top(); // k-th largest19}
Sharpen your skills with hand-picked problems.
LeetCode #215
LeetCode #347
LeetCode #973
LeetCode #703
LeetCode #1337
LeetCode #23
LeetCode #378
LeetCode #632
LeetCode #373
LeetCode #295
LeetCode #480
LeetCode #502
LeetCode #239
LeetCode #1696
LeetCode #1425
LeetCode #253
LeetCode #621
LeetCode #1094
LeetCode #452
LeetCode #1642
LeetCode #767
LeetCode #1383
LeetCode #1882