Back to problems
COMP2521
Heap: k-th Largest
Heap: k-th Largest
Given n integers and k, print the k-th largest value (duplicates rank by value).
Classic: keep a min-heap of size k; after scanning, its root is the k-th largest —O(n log k). Or just sort descending and take indexk-1.
Input: line 1 n k; line 2 n integers.
Output: the k-th largest value.
Example: 6 2 / 3 1 5 2 4 6 -> 5.
Samples
stdin
6 2 3 1 5 2 4 6
expected
5
stdin
1 1 9
expected
9
c-dcc
14