Find the Kth Largest Integer in the Array LeetCode solution in JavaScript

1
var kthLargestNumber = function (nums, k) {
2
const n = nums.length;
3
k = n - k;
4

5
return quickSelect(nums, k, 0, n - 1);
6

7
function quickSelect(arr, selectIdx, left, right) {
8
const pivotIdx = Math.floor(Math.random() * (right - left + 1) + left);
9
const pivotNum = arr[pivotIdx];
10

11
swap(arr, pivotIdx, right);
12

13
let swapIdx = left;
14

15
for (let i = left; i < right; i++) {
16
if (compare(arr[i], pivotNum) < 0) {
17
swap(arr, swapIdx, i);
18
swapIdx++;
19
}
20
}
21

22
swap(arr, swapIdx, right);
23

24
if (swapIdx === selectIdx) return arr[selectIdx];
25

26
if (swapIdx > selectIdx)
27
return quickSelect(arr, selectIdx, left, swapIdx - 1);
28
if (swapIdx < selectIdx)
29
return quickSelect(arr, selectIdx, swapIdx + 1, right);
30
}
31

32
function compare(numStr1, numStr2) {
33
if (numStr1.length > numStr2.length) return 1;
34
if (numStr2.length > numStr1.length) return -1;
35

36
return numStr1.localeCompare(numStr2);
37
}
38

39
function swap(arr, i, j) {
40
[arr[i], arr[j]] = [arr[j], arr[i]];
41
}
42
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0