File tree Expand file tree Collapse file tree 1 file changed +50
-3
lines changed Expand file tree Collapse file tree 1 file changed +50
-3
lines changed Original file line number Diff line number Diff line change @@ -71,14 +71,61 @@ medianFinder.findMedian(); // return 2.0
71
71
## Solution
72
72
73
73
``` javascript
74
-
74
+ var MedianFinder = function () {
75
+ this .arr = [];
76
+ };
77
+
78
+ /**
79
+ * @param {number} num
80
+ * @return {void}
81
+ */
82
+ MedianFinder .prototype .addNum = function (num ) {
83
+ if (! this .arr .length ) {
84
+ this .arr .push (num);
85
+ return ;
86
+ }
87
+ var left = 0 ;
88
+ var right = this .arr .length - 1 ;
89
+ while (left <= right) {
90
+ if (left === right) {
91
+ this .arr .splice (this .arr [left] >= num ? left : (left + 1 ), 0 , num);
92
+ return ;
93
+ }
94
+ var mid = left + Math .floor ((right - left) / 2 );
95
+ if (this .arr [mid] === num) {
96
+ left = mid;
97
+ right = mid;
98
+ } else if (this .arr [mid] > num) {
99
+ right = mid;
100
+ } else {
101
+ left = mid + 1 ;
102
+ }
103
+ }
104
+ };
105
+
106
+ /**
107
+ * @return {number}
108
+ */
109
+ MedianFinder .prototype .findMedian = function () {
110
+ return this .arr .length % 2
111
+ ? this .arr [(this .arr .length - 1 ) / 2 ]
112
+ : (this .arr [this .arr .length / 2 ] + this .arr [this .arr .length / 2 - 1 ]) / 2 ;
113
+
114
+ };
115
+
116
+ /**
117
+ * Your MedianFinder object will be instantiated and called as such:
118
+ * var obj = new MedianFinder()
119
+ * obj.addNum(num)
120
+ * var param_2 = obj.findMedian()
121
+ */
75
122
```
76
123
77
124
** Explain:**
78
125
79
- nope .
126
+ Binary search .
80
127
81
128
** Complexity:**
82
129
83
- * Time complexity : O(n).
130
+ * Time complexity : O(n * log(n) ).
84
131
* Space complexity : O(n).
You can’t perform that action at this time.
0 commit comments