描述:
样例:
Given a non-overlapping interval list which is sorted by start point.
Insert a new interval into it, make sure the list is still in order and non-overlapping
(merge intervals if necessary).
Insert (2, 5)
into [(1,2), (5,9)]
, we get [(1,9)].
Insert (3, 4)
into [(1,2), (5,9)]
, we get [(1,2), (3,4), (5,9)]
.
思路:一开始毫无思路。后来想了一个超级复杂的办法,弯弯绕绕最后完美的超时了。后来参考了九章算法,感觉自己好蠢啊。。。
正确思路:首先将一对新的数据按顺序list中,之后对每对数据的end和下一对数据的start进行比较,进而进行合并处理。
List<Interval> list = new ArrayList();
int i = 0;
while(i < intervals.size() && intervals.get(i).start < newInterval.start ){
i++;
}
intervals.add(i,newInterval); //先放入list中再进行比较
Interval prev = null;
for(Interval inter:intervals){
if(prev==null||prev.end < inter.start){
list.add(inter);
prev = inter;
}else{
prev.end = Math.max(prev.end, inter.end);//这里处理的很奇怪,最后为什么返回list呢?感觉prev在最后并没有保存进list啊
}
}
return list;