A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner.
addRange(int left, int right)
Adds the half-open interval[left, right)
, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval[left, right)
that are not already tracked.
queryRange(int left, int right)
Returns true if and only if every real number in the interval[left, right)
is currently being tracked.
removeRange(int left, int right)
Stops tracking every real number currently being tracked in the interval[left, right)
.
Example 1:
addRange(10, 20): null removeRange(14, 16): null queryRange(10, 14): true (Every number in [10, 14) is being tracked) queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked) queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation)
/* 区间查询问题
* [left, right)
* 每次执行addRange 后进行区间合并即 [ ) [ ) [ )
* 执行queryrange() 如果这个区间被完全覆盖就返回true
* 执行removerange 删除这个区间(删除被覆盖部分的区间并进行拆分)
*
* */
class RangeModule {
private:
map<int,int> m; // 左端点做key 按key自动排序 映射右端点
pair<int, int> find(int left, int right){
// 在map 中找到不小于left和right 的左端点l 左端点r
// 再判断l对应的右端点是否比left 大 大说明left不在这个区间内 right同理
// 每次在查找到后 先合并这段区间(即删除l r 再连接 left right)然后返回合并后的结果
auto l=m.upper_bound(left), r=m.upper_bound(right); // 这里找到的是第一个>=left 或者right的值
if(l!=m.begin() && (--l)->second<left) l++;
if(l==r) return {left, right}; // 没有与任何区间重合
int i=min(l->first, left), j=max((--r)->second, right);
m.erase(l, ++r); // 合并中间区间 即先删除中间全部区间再进行合并
return {i,j};
}
public:
RangeModule() {
}
//查找left 和 right落在的区间 如果落在同一个区间就不用合并了
void addRange(int left, int right) {
auto x = find(left, right);
m[x.first] = x.second;
}
// 查找left 和 right落在的区间 如果落在同一个区间返回true
bool queryRange(int left, int right) {
auto l=m.upper_bound(left);// --l真正对应了第一个>=left位置的区间的右端点
return l!=m.begin() && (--l)->second>=right;
}
// 查找left 和 right落在的区间 并剪断
void removeRange(int left, int right) {
auto x = find(left, right); //先合并left-right区间再删除这个区间 find在查找时已经进行了合并
// 如果合并范围太大了 还要把多余的部分断开 即x.first left right x.second
// 断开为[x.first, left) [right, x.second)
if(left>x.first) m[x.first]=left;
if(x.second>right) m[right] = x.second;
}
};