-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathres.js
50 lines (45 loc) · 989 Bytes
/
res.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 二分法排序 + 查找
* initialize your data structure here.
*/
var MedianFinder = function() {
this.nums = [];
};
/**
* @param {number} num
* @return {void}
*/
MedianFinder.prototype.addNum = function(num) {
//
const bs = (n) => {
let start = 0;
let end = this.nums.length;
while (start < end) {
let mid = (start + end) >> 1;
if (n > this.nums[mid]) {
start = mid + 1;
} else {
end = mid;
}
}
this.nums.splice(start, 0, n);
}
if (this.nums.length) {
bs(num);
} else {
this.nums.push(num);
}
};
/**
* @return {number}
*/
MedianFinder.prototype.findMedian = function() {
const len = this.nums.length;
return len ? len % 2 ? this.nums[Math.floor(len / 2)] : (this.nums[len / 2] + this.nums[len / 2 - 1]) / 2 : null;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* var obj = new MedianFinder()
* obj.addNum(num)
* var param_2 = obj.findMedian()
*/