File tree Expand file tree Collapse file tree 1 file changed +11
-21
lines changed
solution/0200-0299/0295.Find Median from Data Stream Expand file tree Collapse file tree 1 file changed +11
-21
lines changed Original file line number Diff line number Diff line change 1
1
class MedianFinder {
2
- private nums : number [ ] ;
3
-
4
- constructor ( ) {
5
- this . nums = [ ] ;
6
- }
2
+ #minQ = new MinPriorityQueue ( ) ;
3
+ #maxQ = new MaxPriorityQueue ( ) ;
7
4
8
5
addNum ( num : number ) : void {
9
- const { nums } = this ;
10
- let l = 0 ;
11
- let r = nums . length ;
12
- while ( l < r ) {
13
- const mid = ( l + r ) >>> 1 ;
14
- if ( nums [ mid ] < num ) {
15
- l = mid + 1 ;
16
- } else {
17
- r = mid ;
18
- }
6
+ const [ minQ , maxQ ] = [ this . #minQ, this . #maxQ] ;
7
+ maxQ . enqueue ( num ) ;
8
+ minQ . enqueue ( maxQ . dequeue ( ) . element ) ;
9
+ if ( minQ . size ( ) - maxQ . size ( ) > 1 ) {
10
+ maxQ . enqueue ( minQ . dequeue ( ) . element ) ;
19
11
}
20
- nums . splice ( l , 0 , num ) ;
21
12
}
22
13
23
14
findMedian ( ) : number {
24
- const { nums } = this ;
25
- const n = nums . length ;
26
- if ( ( n & 1 ) === 1 ) {
27
- return nums [ n >> 1 ] ;
15
+ const [ minQ , maxQ ] = [ this . #minQ, this . #maxQ] ;
16
+ if ( minQ . size ( ) === maxQ . size ( ) ) {
17
+ return ( minQ . front ( ) . element + maxQ . front ( ) . element ) / 2 ;
28
18
}
29
- return ( nums [ n >> 1 ] + nums [ ( n >> 1 ) - 1 ] ) / 2 ;
19
+ return minQ . front ( ) . element ;
30
20
}
31
21
}
32
22
You can’t perform that action at this time.
0 commit comments