Kth Largest Array Element
Problem statement
Given an unsorted integer array nums and a one-based rank k, return its kth largest value. For this exercise, count every array occurrence, including duplicates. Equivalently, sort all occurrences in nonincreasing order and select position k.
The second-largest task is the case k=2. For example, [5,5,4] has second-largest value5under this positional convention, while its second distinct value would be4. Return the value, not its index. For this exercise, leave nums unchanged.
Function
kthLargest(nums: int[], k: int) → intExamples
Example 1
nums = [5,5,4]k = 2return = 5The descending occurrences are [5,5,4]. Position2contains5, so duplicates are not removed.
Example 2
nums = [3,2,1,5,6,4]k = 2return = 5The descending occurrences are [6,5,4,3,2,1]. Position2contains5.
Constraints
- For this exercise, assume 1 <= nums.length <= 2000.
- For this exercise, assume -1000000 <= nums[i] <= 1000000.
- For this exercise, assume 1 <= k <= nums.length.