Given an integer array nums and an integer k, return the kth largest element in sorted order (not the kth distinct element). Try to solve it without sorting.
The kth largest sits at index n − k in sorted order. Partition around a pivot like quicksort, then continue only in the side that contains that index.
1function findKthLargest(nums: number[], k: number): number {2const target = nums.length - k;3let lo = 0, hi = nums.length - 1;4while (true) {5const pivot = nums[hi];6let p = lo;7for (let i = lo; i < hi; i++)8if (nums[i] <= pivot) { [nums[i], nums[p]] = [nums[p], nums[i]]; p++; }9[nums[p], nums[hi]] = [nums[hi], nums[p]];10if (p === target) return nums[p];11if (p < target) lo = p + 1;12else hi = p - 1;13}14}
Sorted, the answer is at index 4.
Space: play/pause · ←/→: step