File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * Time Complexity: O(logn)
3
+ * Space Complexity: O(n)
4
+ */
5
+
6
+ class MedianFinder {
7
+ public minHeap ;
8
+ public maxHeap ;
9
+
10
+ constructor ( ) {
11
+ this . minHeap = new MinPriorityQueue ( ) ;
12
+ this . maxHeap = new MaxPriorityQueue ( ) ;
13
+ }
14
+
15
+ addNum ( num : number ) : void {
16
+ this . getHeap ( num ) . enqueue ( num ) ;
17
+ this . rebalance ( ) ;
18
+ }
19
+
20
+ findMedian ( ) : number {
21
+ if ( this . minHeap . size ( ) === this . maxHeap . size ( ) ) {
22
+ return ( this . minHeap . front ( ) . element + this . maxHeap . front ( ) . element ) / 2 ;
23
+ }
24
+
25
+ return this . maxHeap . front ( ) . element ;
26
+ }
27
+
28
+ rebalance ( ) {
29
+ if ( this . minHeap . size ( ) + 1 < this . maxHeap . size ( ) ) {
30
+ return this . minHeap . enqueue ( this . maxHeap . dequeue ( ) . element ) ;
31
+ }
32
+
33
+ if ( this . maxHeap . size ( ) < this . minHeap . size ( ) ) {
34
+ return this . maxHeap . enqueue ( this . minHeap . dequeue ( ) . element ) ;
35
+ }
36
+ }
37
+
38
+ getHeap ( num : number ) {
39
+ if ( this . maxHeap . isEmpty ( ) || num <= this . maxHeap . front ( ) . element ) {
40
+ return this . maxHeap ;
41
+ }
42
+
43
+ return this . minHeap ;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Your MedianFinder object will be instantiated and called as such:
49
+ * var obj = new MedianFinder()
50
+ * obj.addNum(num)
51
+ * var param_2 = obj.findMedian()
52
+ */
You can’t perform that action at this time.
0 commit comments