Kth Largest Element in an Array
You get an array of integers and a number k. Return the k-th largest number: the one that would stand k-th if the array were sorted from largest to smallest. Repeats count, so it is not the k-th distinct value. Our example: [5, 9, 2, 9, 4, 7] and k = 3 — the answer is 7, since the two 9s take first and second place.
- input
nums: an array of integers, not sorted, maybe with repeats;k: an integer.- returns
- The
k-th largest number ofnums: the one that would stand at placekifnumswere sorted from largest to smallest. Equal numbers count one by one: the 2nd largest of[5, 5, 4]is5. - constraints
- 1 ≤ nums.length ≤ 10⁴
- 1 ≤ k ≤ nums.length
- −10⁴ ≤ nums[i] ≤ 10⁴
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
function findKthLargest(nums, k) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more heap and top k problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.