Skip to content

Commit 26c9daa

Browse files
authored
Update 2276-count-integers-in-intervals.js
1 parent 73e0fdd commit 26c9daa

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

2276-count-integers-in-intervals.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,45 @@
1+
var CountIntervals = function() {
2+
this.intervals = []
3+
this.ans = 0
4+
};
5+
6+
/**
7+
* @param {number} left
8+
* @param {number} right
9+
* @return {void}
10+
*/
11+
CountIntervals.prototype.add = function(left, right) {
12+
let l = 0, r = this.intervals.length
13+
while (l < r) {
14+
const m = Math.floor((l + r) / 2)
15+
if (this.intervals[m][1] >= left) {
16+
r = m
17+
} else {
18+
l = m + 1
19+
}
20+
}
21+
22+
let index = l
23+
while (index < this.intervals.length && this.intervals[index][0] <= right) {
24+
left = Math.min(left, this.intervals[index][0])
25+
right = Math.max(right, this.intervals[index][1])
26+
this.ans -= this.intervals[index][1] - this.intervals[index][0] + 1
27+
index += 1
28+
}
29+
this.ans += right - left + 1
30+
this.intervals.splice(l, index - l, [left, right])
31+
};
32+
33+
34+
/**
35+
* @return {number}
36+
*/
37+
CountIntervals.prototype.count = function() {
38+
return this.ans
39+
};
40+
41+
// another
42+
143
function binarySearch(l, r, fn) {
244
while (l <= r) {
345
const m = Math.floor((l + r) / 2)

0 commit comments

Comments
 (0)