forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0703-kth-largest-element-in-a-stream.ts
More file actions
73 lines (61 loc) · 2.2 KB
/
0703-kth-largest-element-in-a-stream.ts
File metadata and controls
73 lines (61 loc) · 2.2 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
class KthLargest {
backingArray: number[];
size: number;
constructor(k: number, nums: number[]) {
this.backingArray = [];
this.size = k;
for (const num of nums) this.add(num);
}
add(val: number): number {
const newLength = this.backingArray.push(val);
this.shiftUp(newLength - 1);
if (newLength > this.size) this.pop();
return this.backingArray[0];
}
private pop() {
this.swap(0, this.backingArray.length - 1);
this.backingArray.length -= 1;
this.shiftDown(0);
}
private shiftDown(elementIndex: number) {
let leftChildIndex = elementIndex * 2 + 1;
let rightChildIndex = elementIndex * 2 + 2;
while (
(leftChildIndex < this.backingArray.length &&
this.backingArray[leftChildIndex] <
this.backingArray[elementIndex]) ||
(rightChildIndex < this.backingArray.length &&
this.backingArray[rightChildIndex] <
this.backingArray[elementIndex])
) {
let smallestIndex = leftChildIndex;
if (
rightChildIndex < this.backingArray.length &&
this.backingArray[rightChildIndex] <
this.backingArray[smallestIndex]
) {
smallestIndex = rightChildIndex;
}
this.swap(elementIndex, smallestIndex);
elementIndex = smallestIndex;
leftChildIndex = elementIndex * 2 + 1;
rightChildIndex = elementIndex * 2 + 2;
}
}
private shiftUp(elementIndex: number) {
if (elementIndex === 0) return;
let parentIndex = Math.floor((elementIndex - 1) / 2);
while (
this.backingArray[parentIndex] > this.backingArray[elementIndex]
) {
this.swap(elementIndex, parentIndex);
elementIndex = parentIndex;
parentIndex = Math.floor((elementIndex - 1) / 2);
}
}
private swap(indexA: number, indexB: number) {
const temp = this.backingArray[indexA];
this.backingArray[indexA] = this.backingArray[indexB];
this.backingArray[indexB] = temp;
}
}