-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApril-8-2022-kth-largest.js
94 lines (80 loc) · 2.05 KB
/
April-8-2022-kth-largest.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* @param {number} k
* @param {number[]} nums
*/
class BH {
constructor() {
this.values = [];
}
add(element) {
this.values.push(element);
let index = this.values.length - 1;
const current = this.values[index];
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
let parent = this.values[parentIndex];
if (parent >= current) {
this.values[parentIndex] = current;
this.values[index] = parent;
index = parentIndex;
} else break;
}
}
pop() {
const max = this.values[0];
const end = this.values.pop();
this.values[0] = end;
let index = 0;
const length = this.values.length;
const current = this.values[0];
while (true) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let leftChild, rightChild;
let swap = null;
if (leftChildIndex < length) {
leftChild = this.values[leftChildIndex];
if (leftChild < current) swap = leftChildIndex;
}
if (rightChildIndex < length) {
rightChild = this.values[rightChildIndex];
if (
(swap === null && rightChild < current) ||
(swap !== null && rightChild < leftChild)
)
swap = rightChildIndex;
}
if (swap === null) break;
this.values[index] = this.values[swap];
this.values[swap] = current;
index = swap;
}
return max;
}
}
var KthLargest = function(k, nums) {
this.heap = new BH();
nums.forEach(n => this.heap.add(n));
this.k = k;
};
/**
* @param {number} val
* @return {number}
*/
KthLargest.prototype.add = function(val) {
this.heap.add(val);
while ( this.heap.values.length > this.k ) {
//console.log('add', val, 'size', this.heap.values);
this.heap.pop();
}
const kth = this.heap.values[0];
return kth;
};
/**
* Your KthLargest object will be instantiated and called as such:
* var obj = new KthLargest(k, nums)
* var param_1 = obj.add(val)
*/
function clone(o) {
return JSON.parse(JSON.stringify(o));
}