-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0295-find-median-from-data-stream.ts
52 lines (42 loc) · 1.22 KB
/
0295-find-median-from-data-stream.ts
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
/*
* Time Complexity: O(logn)
* Space Complexity: O(n)
*/
class MedianFinder {
public minHeap;
public maxHeap;
constructor() {
this.minHeap = new MinPriorityQueue();
this.maxHeap = new MaxPriorityQueue();
}
addNum(num: number): void {
this.getHeap(num).enqueue(num);
this.rebalance();
}
findMedian(): number {
if (this.minHeap.size() === this.maxHeap.size()) {
return (this.minHeap.front().element + this.maxHeap.front().element) / 2;
}
return this.maxHeap.front().element;
}
rebalance() {
if (this.minHeap.size() + 1 < this.maxHeap.size()) {
return this.minHeap.enqueue(this.maxHeap.dequeue().element);
}
if (this.maxHeap.size() < this.minHeap.size()) {
return this.maxHeap.enqueue(this.minHeap.dequeue().element);
}
}
getHeap(num: number) {
if (this.maxHeap.isEmpty() || num <= this.maxHeap.front().element) {
return this.maxHeap;
}
return this.minHeap;
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* var obj = new MedianFinder()
* obj.addNum(num)
* var param_2 = obj.findMedian()
*/