/* * @Description: 215. Kth Largest Element in an Array * @Author: libk * @Github: https://github.com/libk */ /** * @param {number[]}nums * @param {number}k * @return {number} */ const findKthLargest = function (nums, k) { let left = 0 let right = nums.length - 1 const target = nums.length - k
const partition = (nums, left, right) => { let random = Math.floor(Math.random() * (right - left + 1)) + left; let povit = nums[random]
;[nums[random], nums[left]] = [nums[left], nums[random]] while (left < right) { while (left < right && nums[right] >= povit) { right-- } if (left < right) { nums[left++] = nums[right] } while (left < right && nums[left] < povit) { left++ } if (left < right) { nums[right--] = nums[left] } } nums[left] = povit return left }
while (true) { let index = partition(nums, left, right) if (index === target) { return nums[index] } elseif (index > target) { right = index - 1 } else { left = index + 1 } } }