Skip to content

Commit 09656cd

Browse files
committed
Changed the solution to using a heap, reducing the time complexity to logn
1 parent b34847c commit 09656cd

File tree

1 file changed

+23
-31
lines changed

1 file changed

+23
-31
lines changed

typescript/0295-find-median-from-data-stream.ts

Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,41 @@
11
class MedianFinder {
2-
private array: number[];
2+
public minHeap;
3+
public maxHeap;
34

45
constructor() {
5-
this.array = [];
6+
this.minHeap = new MinPriorityQueue();
7+
this.maxHeap = new MaxPriorityQueue();
68
}
79

810
addNum(num: number): void {
9-
if (this.array.length === 0) {
10-
this.array.push(num);
11-
return;
12-
}
13-
14-
let left = 0;
15-
let right = this.array.length - 1;
16-
17-
while (left <= right) {
18-
const mid = Math.floor((left + right) / 2);
19-
20-
if (this.array[mid] === num) {
21-
this.array.splice(mid, 0, num);
22-
return;
23-
}
11+
this.getHeap(num).enqueue(num);
12+
this.rebalance();
13+
}
2414

25-
if (this.array[mid] > num) {
26-
right = mid - 1;
27-
} else {
28-
left = mid + 1;
29-
}
15+
findMedian(): number {
16+
if (this.minHeap.size() === this.maxHeap.size()) {
17+
return (this.minHeap.front().element + this.maxHeap.front().element) / 2;
3018
}
3119

32-
this.array.splice(left, 0, num);
20+
return this.maxHeap.front().element;
3321
}
3422

35-
findMedian(): number {
36-
if (this.array.length === 0) {
37-
return 0;
23+
rebalance() {
24+
if (this.minHeap.size() + 1 < this.maxHeap.size()) {
25+
return this.minHeap.enqueue(this.maxHeap.dequeue().element);
3826
}
3927

40-
const mid = Math.floor(this.array.length / 2);
28+
if (this.maxHeap.size() < this.minHeap.size()) {
29+
return this.maxHeap.enqueue(this.minHeap.dequeue().element);
30+
}
31+
}
4132

42-
if (this.array.length % 2 !== 0) {
43-
return this.array[mid];
44-
} else {
45-
return (this.array[mid] + this.array[mid - 1]) / 2;
33+
getHeap(num: number) {
34+
if (this.maxHeap.isEmpty() || num <= this.maxHeap.front().element) {
35+
return this.maxHeap;
4636
}
37+
38+
return this.minHeap;
4739
}
4840
}
4941

0 commit comments

Comments
 (0)