Kth Largest Element in an Array
Given an integer array nums and an integer k, return the kth largest value in the array.
This is the kth largest by position in sorted order, not the kth largest distinct value: duplicates count separately, so in [5, 5, 2] the 2nd largest is 5.
Sorting the whole array works, but try to do better than O(n log n). JavaScript has no built-in heap, so write your own if you use one.
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Examples
Example 1
Input: nums = [3,9,1,7,5], k = 2 Output: 7
Sorted from largest: 9, 7, 5, 3, 1. The 2nd one is 7.
Example 2
Input: nums = [4,2,4,1,3,4], k = 3 Output: 4
Duplicates count separately: from largest the values are 4, 4, 4, 3, 2, 1, so the 3rd largest is still 4.
Example 3
Input: nums = [8], k = 1 Output: 8
A single value is its own 1st largest.
JavaScript you'll use: Heaps and priority queues Sorting and comparators
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
function findKthLargest(nums, k) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.