File tree Expand file tree Collapse file tree 1 file changed +17
-16
lines changed
solution/0200-0299/0295.Find Median from Data Stream Expand file tree Collapse file tree 1 file changed +17
-16
lines changed Original file line number Diff line number Diff line change 1
- /**
2
- * initialize your data structure here.
3
- */
4
1
var MedianFinder = function ( ) {
5
- this . val = [ ] ;
2
+ this . minQ = new MinPriorityQueue ( ) ;
3
+ this . maxQ = new MaxPriorityQueue ( ) ;
6
4
} ;
7
5
8
6
/**
9
7
* @param {number } num
10
8
* @return {void }
11
9
*/
12
10
MedianFinder . prototype . addNum = function ( num ) {
13
- let left = 0 ;
14
- let right = this . val . length ;
15
- while ( left < right ) {
16
- let mid = left + ~ ~ ( ( right - left ) / 2 ) ;
17
- if ( num > this . val [ mid ] ) {
18
- left = mid + 1 ;
19
- } else {
20
- right = mid ;
21
- }
11
+ this . maxQ . enqueue ( num ) ;
12
+ this . minQ . enqueue ( this . maxQ . dequeue ( ) . element ) ;
13
+ if ( this . minQ . size ( ) - this . maxQ . size ( ) > 1 ) {
14
+ this . maxQ . enqueue ( this . minQ . dequeue ( ) . element ) ;
22
15
}
23
- this . val . splice ( left , 0 , num ) ;
24
16
} ;
25
17
26
18
/**
27
19
* @return {number }
28
20
*/
29
21
MedianFinder . prototype . findMedian = function ( ) {
30
- let mid = ~ ~ ( this . val . length / 2 ) ;
31
- return this . val . length % 2 ? this . val [ mid ] : ( this . val [ mid - 1 ] + this . val [ mid ] ) / 2 ;
22
+ if ( this . minQ . size ( ) === this . maxQ . size ( ) ) {
23
+ return ( this . minQ . front ( ) . element + this . maxQ . front ( ) . element ) / 2 ;
24
+ }
25
+ return this . minQ . front ( ) . element ;
32
26
} ;
27
+
28
+ /**
29
+ * Your MedianFinder object will be instantiated and called as such:
30
+ * var obj = new MedianFinder()
31
+ * obj.addNum(num)
32
+ * var param_2 = obj.findMedian()
33
+ */
You can’t perform that action at this time.
0 commit comments