|
| 1 | +/** |
| 2 | + * @param {number[]} nums Unsorted array of numbers. |
| 3 | + * @param {number} k Kth largets element in array to return. |
| 4 | + * @return {number} Value of kth largest element in array. |
| 5 | + * @summary Kth Largest Element in an Array {@link https://leetcode.com/problems/kth-largest-element-in-an-array/} |
| 6 | + * @description Given unsorted array of numbers, return its kth largest element. |
| 7 | + * Space O(1) - Not creating any new arrays. |
| 8 | + * Time O(n) - in worst case N^2. |
| 9 | + */ |
| 10 | +const findKthLargest = (nums, k) => { |
| 11 | + const size = nums.length; |
| 12 | + |
| 13 | + const generateRandom = upTo => Math.floor(Math.random() * upTo); |
| 14 | + |
| 15 | + const partition = (left, right, pivot) => { |
| 16 | + let pivotValue = nums[pivot]; |
| 17 | + |
| 18 | + [nums[pivot], nums[right]] = [nums[right], nums[pivot]]; |
| 19 | + |
| 20 | + let index = left; |
| 21 | + |
| 22 | + for (let i = left; i <= right; i++) { |
| 23 | + if (nums[i] < pivotValue) { |
| 24 | + [nums[index], nums[i]] = [nums[i], nums[index]]; |
| 25 | + index++; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + [nums[index], nums[right]] = [nums[right], nums[index]]; |
| 30 | + |
| 31 | + return index; |
| 32 | + }; |
| 33 | + |
| 34 | + const quickselect = (left, right, target) => { |
| 35 | + if (left === right) nums[left]; |
| 36 | + |
| 37 | + let pivot = left + generateRandom(right - left + 1); |
| 38 | + |
| 39 | + pivot = partition(left, right, pivot); |
| 40 | + |
| 41 | + if (target === pivot) return nums[target]; |
| 42 | + else if (target < pivot) return quickselect(left, pivot - 1, target); |
| 43 | + return quickselect(pivot + 1, right, target); |
| 44 | + }; |
| 45 | + |
| 46 | + return quickselect(0, size - 1, size - k); |
| 47 | +}; |
0 commit comments