File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time complexity: O(n)
2+ // Space complexity: O(n)
3+
4+ var MedianFinder = function ( ) {
5+ this . arr = [ ] ;
6+ } ;
7+
8+ /**
9+ * @param {number } num
10+ * @return {void }
11+ */
12+ MedianFinder . prototype . addNum = function ( num ) {
13+ if ( this . arr . length === 0 ) {
14+ this . arr . push ( num ) ;
15+ return ;
16+ }
17+
18+ let left = 0 ;
19+ let right = this . arr . length - 1 ;
20+
21+ while ( left <= right ) {
22+ const mid = Math . floor ( ( left + right ) / 2 ) ;
23+
24+ if ( this . arr [ mid ] > num ) {
25+ right = mid - 1 ;
26+ continue ;
27+ }
28+
29+ left = mid + 1 ;
30+ }
31+
32+ // insert in left
33+ const sliced = this . arr . slice ( left ) ;
34+ this . arr = [ ...this . arr . slice ( 0 , left ) , num , ...sliced ] ;
35+ } ;
36+
37+ /**
38+ * @return {number }
39+ */
40+ MedianFinder . prototype . findMedian = function ( ) {
41+ if ( this . arr . length % 2 === 0 ) {
42+ return (
43+ ( this . arr [ this . arr . length / 2 ] + this . arr [ this . arr . length / 2 - 1 ] ) / 2
44+ ) ;
45+ }
46+
47+ return this . arr [ ( this . arr . length - 1 ) / 2 ] ;
48+ } ;
49+
50+ /**
51+ * Your MedianFinder object will be instantiated and called as such:
52+ * var obj = new MedianFinder()
53+ * obj.addNum(num)
54+ * var param_2 = obj.findMedian()
55+ */
You can’t perform that action at this time.
0 commit comments