Find the k-th largest value in an unsorted integer array.
Kth Largest Element in an Array
Given an integer array nums and an integer k, return the k-th largest element in the array.
The k-th largest element is the element that would appear at position k if the array were sorted in descending order. Duplicates are allowed, and they are treated as separate elements.
You should solve the problem without assuming the array is already sorted.
Input Format
nums: an integer arrayk: a positive integer
The exact function signature depends on the platform.
Output Format
Return a single integer: the k-th largest element in nums.
Constraints
1 <= k <= nums.length- Array values may be negative, zero, or positive
- Duplicates may appear in
nums
Example 1
Input
nums = [3,2,1,5,6,4], k = 2
Output
5
Explanation
Sorted in descending order: [6,5,4,3,2,1]. The 2nd largest element is 5.
Example 2
Input
nums = [3,2,3,1,2,4,5,5,6], k = 4
Output
4
Explanation
Sorted in descending order: [6,5,5,4,3,3,2,2,1]. The 4th largest element is 4.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.