Skip to content

Commit fc9e825

Browse files
authored
Merge pull request #3382 from arkadiusz-wrzawinski/typescript-0703-kth-largest-element-in-a-stream
Create 0703-kth-largest-element-in-a-stream.ts
2 parents 9bb3a68 + ac8e881 commit fc9e825

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Diff for: typescript/0703-kth-largest-element-in-a-stream.ts

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class KthLargest {
2+
backingArray: number[];
3+
size: number;
4+
5+
constructor(k: number, nums: number[]) {
6+
this.backingArray = [];
7+
this.size = k;
8+
for(const num of nums) this.add(num)
9+
}
10+
11+
add(val: number): number {
12+
const newLength = this.backingArray.push(val)
13+
this.shiftUp(newLength - 1);
14+
15+
if (newLength > this.size) this.pop();
16+
17+
return this.backingArray[0];
18+
}
19+
20+
private pop() {
21+
this.swap(0, this.backingArray.length - 1)
22+
this.backingArray.length -= 1;
23+
this.shiftDown(0)
24+
}
25+
26+
private shiftDown(elementIndex: number) {
27+
let leftChildIndex = elementIndex * 2 + 1;
28+
let rightChildIndex = elementIndex * 2 + 2;
29+
30+
while ((leftChildIndex < this.backingArray.length && this.backingArray[leftChildIndex] < this.backingArray[elementIndex])
31+
|| (rightChildIndex < this.backingArray.length && this.backingArray[rightChildIndex] < this.backingArray[elementIndex])) {
32+
let smallestIndex = leftChildIndex;
33+
if (rightChildIndex < this.backingArray.length && this.backingArray[rightChildIndex] < this.backingArray[smallestIndex]) {
34+
smallestIndex = rightChildIndex
35+
}
36+
37+
this.swap(elementIndex, smallestIndex);
38+
39+
elementIndex = smallestIndex;
40+
leftChildIndex = elementIndex * 2 + 1;
41+
rightChildIndex = elementIndex * 2 + 2;
42+
}
43+
}
44+
45+
private shiftUp(elementIndex: number) {
46+
if (elementIndex === 0) return;
47+
48+
let parentIndex = Math.floor((elementIndex - 1) / 2);
49+
while (this.backingArray[parentIndex] > this.backingArray[elementIndex]) {
50+
this.swap(elementIndex, parentIndex);
51+
elementIndex = parentIndex;
52+
parentIndex = Math.floor((elementIndex - 1) / 2);
53+
}
54+
}
55+
56+
private swap(indexA: number, indexB: number) {
57+
const temp = this.backingArray[indexA];
58+
this.backingArray[indexA] = this.backingArray[indexB];
59+
this.backingArray[indexB] = temp;
60+
}
61+
}

0 commit comments

Comments
 (0)