Skip to content

Commit 646a399

Browse files
authored
Create 2276.Count-Integers-in-Intervals.cpp
1 parent f2d87dd commit 646a399

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class CountIntervals {
2+
map<int,int>Map;
3+
int ret = 0;
4+
public:
5+
CountIntervals() {
6+
7+
}
8+
9+
void add(int left, int right)
10+
{
11+
unordered_set<int>temp;
12+
13+
int start = left;
14+
auto iter = Map.lower_bound(left);
15+
if (iter!=Map.begin() && prev(iter)->second>=start)
16+
{
17+
iter = prev(iter);
18+
temp.insert(iter->first);
19+
start = min(start, iter->first);
20+
}
21+
22+
int end = right;
23+
iter = Map.lower_bound(left);
24+
if (iter!=Map.begin())
25+
end = max(end, prev(iter)->second);
26+
while (iter!=Map.end() && iter->first<=end)
27+
{
28+
temp.insert(iter->first);
29+
end = max(end, iter->second);
30+
iter = next(iter);
31+
}
32+
33+
for (int x: temp)
34+
{
35+
ret -= Map[x]-x+1;
36+
Map.erase(x);
37+
}
38+
ret += end-start+1;
39+
Map[start] = end;
40+
}
41+
42+
int count() {
43+
return ret;
44+
}
45+
};
46+
47+
/**
48+
* Your CountIntervals object will be instantiated and called as such:
49+
* CountIntervals* obj = new CountIntervals();
50+
* obj->add(left,right);
51+
* int param_2 = obj->count();
52+
*/

0 commit comments

Comments
 (0)