Skip to content

Commit 012343e

Browse files
committed
find median from data stream solution
1 parent 34f444a commit 012343e

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class MedianFinder {
2+
private left: PriorityQueue<number>;
3+
private right: PriorityQueue<number>;
4+
5+
constructor() {
6+
this.left = new PriorityQueue<number>((a, b) => b - a); // 최대 힙
7+
this.right = new PriorityQueue<number>((a, b) => a - b); // 최소 힙
8+
}
9+
10+
addNum(num: number): void {
11+
if (this.left.isEmpty() || num <= this.left.front()) {
12+
this.left.enqueue(num);
13+
} else {
14+
this.right.enqueue(num);
15+
}
16+
17+
if (this.left.size() > this.right.size() + 1) {
18+
this.right.enqueue(this.left.dequeue());
19+
}
20+
21+
if (this.right.size() > this.left.size()) {
22+
this.left.enqueue(this.right.dequeue());
23+
}
24+
25+
if (!this.right.isEmpty() && this.left.front() > this.right.front()) {
26+
const maxValue = this.left.dequeue();
27+
28+
this.right.enqueue(maxValue);
29+
}
30+
}
31+
32+
findMedian(): number {
33+
let result = 0;
34+
35+
if (this.left.size() === this.right.size()) {
36+
result = (this.left.front() + this.right.front()) / 2;
37+
} else if (this.left.size() === this.right.size() + 1) {
38+
result = this.left.front();
39+
}
40+
41+
return result;
42+
}
43+
}
44+
45+
/**
46+
* Your MedianFinder object will be instantiated and called as such:
47+
* var obj = new MedianFinder()
48+
* obj.addNum(num)
49+
* var param_2 = obj.findMedian()
50+
*/

0 commit comments

Comments
 (0)