LeetCode-215. Kth Largest Element in an Array

问题描述

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example :

1
2
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Constraints:

  • 1 <= k <= nums.length <= 104
  • -104 <= nums[i] <= 104

解答

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
41
42
43
44
45
46
47
48
49
/*
* @Description: 215. Kth Largest Element in an Array
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
const findKthLargest = function (nums, k) {
let left = 0
let right = nums.length - 1
const target = nums.length - k

const partition = (nums, left, right) => {
let random = Math.floor(Math.random() * (right - left + 1)) + left;
let povit = nums[random]

;[nums[random], nums[left]] = [nums[left], nums[random]]
while (left < right) {
while (left < right && nums[right] >= povit) {
right--
}
if (left < right) {
nums[left++] = nums[right]
}
while (left < right && nums[left] < povit) {
left++
}
if (left < right) {
nums[right--] = nums[left]
}
}
nums[left] = povit
return left
}

while (true) {
let index = partition(nums, left, right)
if (index === target) {
return nums[index]
} else if (index > target) {
right = index - 1
} else {
left = index + 1
}
}
}