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