Kth Largest Element in an Array
Given an integer array nums and an integer k, return the kth largest element in the array. This is the kth largest in sorted order, not the kth distinct element. You must solve it without fully sorting.
Open official problem prompt ↗Find the value that would sit at position k from the top if the array were sorted in descending order, without paying for a full sort.
Imagine judging a talent show and only keeping the top k acts on a shortlist. Each new act bumps out the current weakest of the shortlist if it is better. At the end, the weakest act still on the shortlist is exactly the kth best overall.
- Input
- nums = [3, 2, 1, 5, 6, 4], k = 2
- Output
- 5
- Why
- Sorted descending is [6, 5, 4, 3, 2, 1]; the 2nd largest is 5.
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4