forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path715.Range-Module.cpp
78 lines (68 loc) · 1.96 KB
/
715.Range-Module.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class RangeModule {
map<int,int>Map;
public:
RangeModule()
{
Map.clear();
}
void addRange(int left, int right)
{
auto pos1 = Map.lower_bound(left);
int leftboundary=left;
if (pos1!=Map.begin() && prev(pos1,1)->second>=left)
leftboundary = prev(pos1,1)->first;
auto pos2 = Map.upper_bound(right);
int rightboundary = right;
if (pos2!=Map.begin())
rightboundary = max(right, prev(pos2,1)->second);
Map.erase(pos1,pos2);
Map[leftboundary]=rightboundary;
/*
for (auto a:Map)
cout<<a.first<<":"<<a.second<<endl;
cout<<"added"<<endl;
*/
}
bool queryRange(int left, int right)
{
auto pos = Map.upper_bound(left);
if (pos==Map.begin())
return false;
pos = prev(pos,1);
return (pos->second>=right);
}
void removeRange(int left, int right)
{
auto pos1 = Map.lower_bound(left);
bool flag1=0;
int temp1;
if (pos1!=Map.begin() && prev(pos1,1)->second > left)
{
temp1 = prev(pos1,1)->first;
flag1=1;
}
auto pos2 = Map.lower_bound(right);
int temp2;
bool flag2=0;
if (pos2!=Map.begin() && prev(pos2,1)->second > right)
{
temp2 = prev(pos2,1)->second;
flag2=1;
}
Map.erase(pos1,pos2);
if (flag1) Map[temp1]=left;
if (flag2) Map[right]=temp2;
/*
for (auto a:Map)
cout<<a.first<<":"<<a.second<<endl;
cout<<"removed"<<endl;
*/
}
};
/**
* Your RangeModule object will be instantiated and called as such:
* RangeModule obj = new RangeModule();
* obj.addRange(left,right);
* bool param_2 = obj.queryRange(left,right);
* obj.removeRange(left,right);
*/