-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathres.js
42 lines (37 loc) · 799 Bytes
/
res.js
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
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function(nums, k) {
const len = nums.length;
const target = len - k;
let left = 0, right = len-1;
const swap = (a, b) => {
const temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
const partition = (start, end) => {
const pivot = nums[left];
let lindex = left;
for (let i = left+1; i <= end; i++) {
const element = nums[i];
if (element < pivot) {
swap(++lindex, i);
}
}
swap(lindex, left);
return lindex;
}
while(true) {
let index = partition(left, right);
if (index === target) {
return nums[index];
} else if (index < target) {
left = index+1;
} else {
right = index-1;
}
}
};