Skip to content

Commit 1a4dfef

Browse files
authored
Update Solution.ts
1 parent e1e587e commit 1a4dfef

File tree

1 file changed

+16
-19
lines changed
  • solution/0200-0299/0215.Kth Largest Element in an Array

1 file changed

+16
-19
lines changed
Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
11
function findKthLargest(nums: number[], k: number): number {
22
const n = nums.length;
3-
const swap = (i: number, j: number) => {
4-
[nums[i], nums[j]] = [nums[j], nums[i]];
5-
};
6-
const sort = (l: number, r: number) => {
7-
if (l + 1 > k || l >= r) {
8-
return;
3+
k = n - k;
4+
const quickSort = (l: number, r: number): number => {
5+
if (l === r) {
6+
return nums[l];
97
}
10-
swap(l, l + Math.floor(Math.random() * (r - l)));
11-
const num = nums[l];
12-
let mark = l;
13-
for (let i = l + 1; i < r; i++) {
14-
if (nums[i] > num) {
15-
mark++;
16-
swap(i, mark);
8+
let [i, j] = [l - 1, r + 1];
9+
const x = nums[(l + r) >> 1];
10+
while (i < j) {
11+
while (nums[++i] < x);
12+
while (nums[--j] > x);
13+
if (i < j) {
14+
[nums[i], nums[j]] = [nums[j], nums[i]];
1715
}
1816
}
19-
swap(l, mark);
20-
21-
sort(l, mark);
22-
sort(mark + 1, r);
17+
if (j < k) {
18+
return quickSort(j + 1, r);
19+
}
20+
return quickSort(l, j);
2321
};
24-
sort(0, n);
25-
return nums[k - 1];
22+
return quickSort(0, n - 1);
2623
}

0 commit comments

Comments
 (0)