|
| 1 | +var CountIntervals = function () { |
| 2 | + this.root = new Node(1, 10 ** 9) |
| 3 | +} |
| 4 | + |
| 5 | +/** |
| 6 | + * @param {number} left |
| 7 | + * @param {number} right |
| 8 | + * @return {void} |
| 9 | + */ |
| 10 | +CountIntervals.prototype.add = function (left, right) { |
| 11 | + this.root.addInterval(left, right) |
| 12 | +} |
| 13 | + |
| 14 | +/** |
| 15 | + * @return {number} |
| 16 | + */ |
| 17 | +CountIntervals.prototype.count = function () { |
| 18 | + return this.root.total |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Your CountIntervals object will be instantiated and called as such: |
| 23 | + * var obj = new CountIntervals() |
| 24 | + * obj.add(left,right) |
| 25 | + * var param_2 = obj.count() |
| 26 | + */ |
| 27 | + |
| 28 | +class Node { |
| 29 | + constructor(min, max) { |
| 30 | + this.min = min |
| 31 | + this.max = max |
| 32 | + this.currentMin = -1 |
| 33 | + this.currentMax = -1 |
| 34 | + this.total = 0 |
| 35 | + this.left = null |
| 36 | + this.right = null |
| 37 | + } |
| 38 | + |
| 39 | + addInterval(left, right) { |
| 40 | + if (this.currentMin < 0) { |
| 41 | + this.currentMin = left |
| 42 | + this.currentMax = right |
| 43 | + this.total = right - left + 1 |
| 44 | + return this.total |
| 45 | + } |
| 46 | + |
| 47 | + const mid = (this.min + this.max) >> 1 |
| 48 | + |
| 49 | + if (this.left) { |
| 50 | + if (left <= mid) this.left.addInterval(left, Math.min(mid, right)) |
| 51 | + if (right > mid) this.right.addInterval(Math.max(mid + 1, left), right) |
| 52 | + |
| 53 | + this.total = this.left.total + this.right.total |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + if (left <= this.currentMax + 1 && right >= this.currentMin - 1) { |
| 58 | + this.currentMin = Math.min(this.currentMin, left) |
| 59 | + this.currentMax = Math.max(this.currentMax, right) |
| 60 | + this.total = this.currentMax - this.currentMin + 1 |
| 61 | + return |
| 62 | + } |
| 63 | + this.left = new Node(this.min, mid) |
| 64 | + this.right = new Node(mid + 1, this.max) |
| 65 | + |
| 66 | + if (left <= mid) this.left.addInterval(left, Math.min(mid, right)) |
| 67 | + if (right > mid) this.right.addInterval(Math.max(left, mid + 1), right) |
| 68 | + if (this.currentMin <= mid) |
| 69 | + this.left.addInterval(this.currentMin, Math.min(mid, this.currentMax)) |
| 70 | + if (this.currentMax > mid) |
| 71 | + this.right.addInterval( |
| 72 | + Math.max(mid + 1, this.currentMin), |
| 73 | + this.currentMax |
| 74 | + ) |
| 75 | + |
| 76 | + this.total = this.left.total + this.right.total |
| 77 | + } |
| 78 | +} |
0 commit comments