-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01.js
65 lines (59 loc) · 1.48 KB
/
01.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 215. 数组中的第K个最大元素
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
class MinHeap {
constructor(k) {
this.arr = [];
this.size = 0;
this.max = k;
}
push(val) {
this.arr.push(val);
this.size++;
if (this.size > 1) {
let cur = this.size - 1,
parent = (cur - 1) >> 1;
while (cur > 0 && this.arr[cur] < this.arr[parent]) {
[this.arr[cur], this.arr[parent]] = [this.arr[parent], this.arr[cur]];
cur = parent;
parent = (cur - 1) >> 1;
}
}
if (this.size > this.max) this.pop();
}
pop() {
this.arr[0] = this.arr.pop();
this.size--;
let cur = 0,
childl = 1,
childr = 2;
while (
(childl < this.size && this.arr[childl] < this.arr[cur]) ||
(childr < this.size && this.arr[childr] < this.arr[cur])
) {
if (childr < this.size && this.arr[childr] < this.arr[childl]) {
[this.arr[childr], this.arr[cur]] = [this.arr[cur], this.arr[childr]];
cur = childr;
} else {
[this.arr[childl], this.arr[cur]] = [this.arr[cur], this.arr[childl]];
cur = childl;
}
childl = cur * 2 + 1;
childr = cur * 2 + 2;
}
}
top() {
return this.arr[0];
}
}
var findKthLargest = function (nums, k) {
const heap = new MinHeap(k);
for (let i = 0; i < nums.length; i++) {
if (heap.size < k || nums[i] > heap.top()) heap.push(nums[i]);
}
console.log(heap.arr);
return heap.arr[0];
};