0%

数组中的第 K 个最大元素

题目链接:
https://leetcode-cn.com/problems/kth-largest-element-in-an-array/

解法分析:快排变种

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
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
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;
}
};

参考题解:
https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/partitionfen-er-zhi-zhi-you-xian-dui-lie-java-dai-/

本文标题:数组中的第 K 个最大元素

文章作者:Flower-F

发布时间:2022年01月08日 - 18:59

最后更新:2022年01月19日 - 16:40

-------------本文结束,感谢您的阅读-------------

欢迎关注我的其它发布渠道