LeetCode 715. Range 模块
原题链接
困难
作者:
zchuber
,
2021-03-19 01:35:04
,
所有人可见
,
阅读 4
class RangeModule {
class Node{
int left, right;
public Node(int left,int right){
this.left=left;
this.right=right;
}
}
<!--主要思路,对不同的区间进行排序,利用二分法定位待处理区间在整个的集合中的大致位置,然后通过遍历的方式依次判断集合中的区间和待处理区间进行合并和删除处理-->
TreeSet<Node> set;
public RangeModule() {
set = new TreeSet<>((a,b)->(a.right == b.right ? a.left - b.left : a.right - b.right));
}
public void addRange(int left, int right) {
Iterator it=set.tailSet(new Node(0,left)).iterator();
while(it.hasNext()){
Node node=(Node) it.next();
if(right<node.left){
break;
}
left=Math.min(left,node.left);
right=Math.max(right,node.right);
it.remove();
}
set.add(new Node(left, right));
}
public boolean queryRange(int left, int right) {
if(set.isEmpty()){
return false;
}
Node lower=set.lower(new Node(left,right));
if(lower!=null&&lower.left<=left&&lower.right>=right) return true;
Node next=lower==null?set.first():set.higher(lower);
if(next!=null&&next.left<=left&&next.right>=right) return true;
return false;
}
public void removeRange(int left, int right) {
Iterator it=set.tailSet(new Node(0,left)).iterator();
List<Node> list=new ArrayList();
while(it.hasNext()){
Node node=(Node)it.next();
if(right<node.left) break;
if(node.left<left) list.add(new Node(node.left,left));
if(node.right>right)list.add(new Node(right,node.right));
it.remove();
}
set.addAll(list);
}
}