Solution 1. Use map
class RangeModule {
map<int,int> m;
public:
RangeModule() {
}
void addRange(int left, int right) {
auto l = m.upper_bound(left), r = m.upper_bound(right);
if(l != m.begin()) {
l--;
if(l->second < left) l++;
}
if(l != r) {
left = min(left, l->first);
r--;
if(right < r->second) right = r->second;
r++;
m.erase(l,r);
}
m[left] = right;
}
bool queryRange(int left, int right) {
auto l = m.upper_bound(left);
if(l!=m.begin()) {
l--;
return l->second >= right;
}
return false;
}
void removeRange(int left, int right) {
auto l = m.upper_bound(left), r = m.upper_bound(right);
if(l != m.begin()) {
l--;
if(l->second < left) l++;
}
if(l==r) return;
int l1 = min(l->first, left);
r--;
int r1 = max(r->second, right);
r++;
m.erase(l,r);
if(l1 < left) m[l1] = left;
if(right< r1) m[right] = r1;
}
};
class RangeModule {
vector<int> v;
public:
RangeModule() {
}
void addRange(int left, int right) {
if(v.empty()) { v= {left, right}; return;}
auto l = lower_bound(v.begin(), v.end(), left);
auto r = upper_bound(v.begin(), v.end(), right);
int i = l - v.begin();
int j = r - v.begin();
if(l == r) {
if(i%2 == 0) {
l = v.insert(l, right);
v.insert(l, left);
}
return;
}
if(i%2 == 0) { *l = left; l++;}
if(j%2 == 0) { *l = right; l++; }
else { *l = *r; l++; r++;}
if(l<r) v.erase(l, r);
}
bool queryRange(int left, int right) {
// note that here l = upper_bound(..., left) and r = lower_bound(..., right)
auto l = upper_bound(v.begin(), v.end(), left);
auto r = lower_bound(v.begin(), v.end(), right);
int i = l - v.begin();
return (i%2 != 0) && l == r;
}
void removeRange(int left, int right) {
if(v.empty()) { return;}
auto l = lower_bound(v.begin(), v.end(), left);
auto r = upper_bound(v.begin(), v.end(), right);
int i = l - v.begin();
int j = r - v.begin();
if(l==r) {
if(i%2 != 0) {
l = v.insert(l, right);
v.insert(l, left);
}
return;
}
if(j%2 != 0) { r--; *r = right;}
if(i%2 != 0) { *l = left; l++;}
if(l<r) v.erase(l,r);
}
};
No comments:
Post a Comment