-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path215.js
More file actions
80 lines (70 loc) · 1.85 KB
/
Copy path215.js
File metadata and controls
80 lines (70 loc) · 1.85 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class MaxHeap {
q = [];
length = 0;
insert(val){
this.q[this.length] = val;
this.length++;
this.heapifyUp(this.length - 1);
}
peek(){
if (this.length === 1) {
this.length--;
return this.q.shift();
}
const max = this.q[0];
this.q[0] = this.q.pop();
this.length--;
this.heapifyDown(0);
return max;
}
heapifyUp(id){
const parentId = this.getParentId(id);
const parentVal = this.q[parentId];
const val = this.q[id];
if (val > parentVal) {
this.q[id] = parentVal;
this.q[parentId] = val;
this.heapifyUp(parentId);
}
}
heapifyDown(id){
const leftChildId = this.getLeftChildId(id);
const leftChildVal = this.q[leftChildId];
const rightChildId = this.getRightChildId(id);
const rightChildVal = this.q[rightChildId];
const val = this.q[id];
if (val < leftChildVal && (leftChildVal >= rightChildVal || rightChildVal === undefined)) {
this.q[id] = leftChildVal;
this.q[leftChildId] = val;
this.heapifyDown(leftChildId);
} else if (val < rightChildVal && rightChildVal > leftChildVal) {
this.q[id] = rightChildVal;
this.q[rightChildId] = val;
this.heapifyDown(rightChildId);
}
}
getParentId(id){
return Math.floor((id - 1) / 2);
}
getLeftChildId(id){
return id * 2 + 1;
}
getRightChildId(id){
return id * 2 + 2;
}
}
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function(nums, k) {
const heap = new MaxHeap();
for (const num of nums) {
heap.insert(num);
}
for (let i = 1; i < k; i++) {
heap.peek();
}
return heap.peek();
};