Skip to content

Commit 73e0fdd

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

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

2276-count-integers-in-intervals.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,83 @@
1+
function binarySearch(l, r, fn) {
2+
while (l <= r) {
3+
const m = Math.floor((l + r) / 2)
4+
if (fn(m)) {
5+
l = m + 1
6+
} else {
7+
r = m - 1
8+
}
9+
}
10+
return r
11+
}
12+
13+
var CountIntervals = function () {
14+
this.intervals = []
15+
this.size = 0
16+
}
17+
18+
/**
19+
* @param {number} left
20+
* @param {number} right
21+
* @return {void}
22+
*/
23+
CountIntervals.prototype.add = function (left, right) {
24+
const intervals = this.intervals
25+
if (!intervals.length) {
26+
intervals.push({ left, right })
27+
this.size += right - left + 1
28+
} else if (left > intervals[intervals.length - 1].right) {
29+
intervals.push({ left, right })
30+
this.size += right - left + 1
31+
} else if (right < intervals[0].left) {
32+
intervals.unshift({ left, right })
33+
this.size += right - left + 1
34+
} else {
35+
const i = binarySearch(0, intervals.length - 1, (x) => {
36+
return intervals[x].left < left
37+
})
38+
let j,
39+
start,
40+
end,
41+
sum = 0
42+
if (i < 0 || intervals[i].right < left) {
43+
j = i + 1
44+
start = left
45+
end = right
46+
} else {
47+
j = i
48+
start = intervals[j].left
49+
end = right
50+
}
51+
let first = -1
52+
while (j < intervals.length && right >= intervals[j].left) {
53+
if (first < 0) first = j
54+
end = Math.max(end, intervals[j].right)
55+
sum += intervals[j].right - intervals[j].left + 1
56+
j++
57+
}
58+
// delete [first, j)
59+
// console.log('delete', j - first, '-', first, j)
60+
this.size += end - start + 1 - sum
61+
if (first < 0) {
62+
this.intervals.splice(i + 1, 0, { left: start, right: end })
63+
} else {
64+
this.intervals.splice(first, j - first, { left: start, right: end })
65+
}
66+
}
67+
}
68+
69+
/**
70+
* @return {number}
71+
*/
72+
CountIntervals.prototype.count = function () {
73+
return this.size
74+
}
75+
76+
77+
// another
78+
79+
80+
181
var CountIntervals = function () {
282
this.root = new Node(1, 10 ** 9)
383
}

0 commit comments

Comments
 (0)