1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
var findKthLargest = function (nums, k) { let left = 0, right = nums.length - 1; let target = nums.length - k; while (left <= right) { const index = partition(nums, left, right); if (index === target) { return nums[index]; } else if (index < target) { left = index + 1; } else if (index > target) { right = index - 1; } } return -1;
function partition(nums, left, right) { if (right > left) { let randomIndex = Math.floor(Math.random() * (right - left)) + left + 1; [nums[left], nums[randomIndex]] = [nums[randomIndex], nums[left]]; }
const pivot = nums[left]; let i = left, j = right;
while (i < j) { while (nums[j] >= pivot && i < j) j--; while (nums[i] <= pivot && i < j) i++;
[nums[i], nums[j]] = [nums[j], nums[i]]; } [nums[i], nums[left]] = [nums[left], nums[i]];
return i; } };
|