【分析】用两个TreeMap分别维护一重区间和二重区间,对于新加入的区间先检查是否在二重区间,不在的话循环检查一重区间的交集,把交集纳入二重区间,同时删除查找到的已经在一重区间中的元素,最后把合并后区间加入一重区间即可。
class MyCalendarTwo {
TreeMap<Integer, Integer> se = new TreeMap();
TreeMap<Integer, Integer> db = new TreeMap();
public MyCalendarTwo() {
}
public boolean book(int start, int end) {
end -= 1;
// 检查是否在二重区间中有交集
Integer key = db.floorKey(end);
if(key != null){
int right = db.get(key);
if(right >= start) {
return false;
}
}
// 检查一重区间的交集
key = se.floorKey(end);
if(key != null){
// 可能有多个
while(key != null){
int right = se.get(key);
if(right >= start){
// 获取重叠部分纳入二重区间
int dl = Math.max(key, start);
int dr = Math.min(right, end);
db.put(dl, dr);
// 删除原来一重区间的小区间
se.remove(key);
// 合并
start = Math.min(key, start);
end = Math.max(end, right);
key = se.floorKey(end);
}else{
break;
}
}
se.put(start, end);
}else{
se.put(start, end);
}
return true;
}
}
/**
* Your MyCalendarTwo object will be instantiated and called as such:
* MyCalendarTwo obj = new MyCalendarTwo();
* boolean param_1 = obj.book(start,end);
*/