设置新插入的区间为pre,当pre和cur没交集且pre在前面(pre.end<cur.start),则添加pre,没交集且pre在后面(cur.end<pre.start),则添加cur。若有交集,则更新pre。
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> list = new LinkedList<>();
Interval pre = newInterval;
for(Interval curr: intervals){
if(pre.end < curr.start) {
list.add(pre);
pre = curr;
} else if (curr.end < pre.start) { //Here is the difference.
list.add(curr);
}
else {
pre.start = Math.min(pre.start, curr.start);
pre.end = Math.max(pre.end, curr.end);
}
}
list.add(pre);
return list;
}
本文介绍了一种区间合并算法,该算法通过遍历一系列区间并进行比较来实现区间合并。对于新插入的区间,如果它与当前区间没有交集并且位置在前或在后,则直接添加;若存在交集,则更新区间范围。

842

被折叠的 条评论
为什么被折叠?



