File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * initialize your data structure here.
3
+ */
4
+ const MedianFinder = function ( ) {
5
+ this . arr = [ ] ;
6
+ } ;
7
+ /**
8
+ * @param {number } num
9
+ * @return {void }
10
+ */
11
+ MedianFinder . prototype . addNum = function ( num ) {
12
+ const bs = n => {
13
+ let start = 0 ;
14
+ let end = this . arr . length ;
15
+ while ( start < end ) {
16
+ let mid = ~ ~ ( ( start + end ) / 2 ) ;
17
+ if ( n > this . arr [ mid ] ) start = mid + 1 ;
18
+ else end = mid ;
19
+ }
20
+ this . arr . splice ( start , 0 , n ) ;
21
+ } ;
22
+ if ( this . arr . length === 0 ) this . arr . push ( num ) ;
23
+ else bs ( num ) ;
24
+ } ;
25
+
26
+ /**
27
+ * @return {number }
28
+ */
29
+ MedianFinder . prototype . findMedian = function ( ) {
30
+ const mid = ~ ~ ( this . arr . length / 2 ) ;
31
+ return this . arr . length % 2 === 0
32
+ ? ( this . arr [ mid - 1 ] + this . arr [ mid ] ) / 2
33
+ : this . arr [ mid ] ;
34
+ } ;
35
+ /**
36
+ * Your MedianFinder object will be instantiated and called as such:
37
+ * var obj = new MedianFinder()
38
+ * obj.addNum(num)
39
+ * var param_2 = obj.findMedian()
40
+ */
You can’t perform that action at this time.
0 commit comments