mediumHeaps target 25 min
Kth largest number
You get a list of integers nums and a number k. Return the kth largest number: the one at position k, counting from 1, if nums were sorted from largest to smallest.
Repeated values count separately. In [5, 5, 4] the second largest is 5, not 4.
Example 1
Input
nums = [7, 2, 9, 4, 5], k = 2Output7Sorted from largest: 9, 7, 5, 4, 2. Position 2 holds 7.
Example 2
Input
nums = [6, 3, 6, 1, 6, 2], k = 3Output6Sorted from largest: 6, 6, 6, 3, 2, 1. The three 6s fill positions 1 to 3.
Example 3
Input
nums = [-5, -1, -8], k = 3Output-8When k is the length of the list, the answer is the smallest number.
Constraints
1 ≤ k ≤ len(nums) ≤ 105
-105 ≤ nums[i] ≤ 105
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.