Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in
as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in
as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
题目:在上一题的基础上,在加一个新的对象,也是合并的要求。
思路:直接加入到list里,用上一题的方法就可以了。
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
intervals.add(newInterval);
if (intervals == null || intervals.size() <= 1) {
return intervals;
}
Collections.sort(intervals, new IntervalComparator());
ArrayList<Interval> result = new ArrayList<Interval>();
Interval last = intervals.get(0);
for (int i = 1; i < intervals.size(); i++) {
Interval curt = intervals.get(i);
if (curt.start <= last.end ){
last.end = Math.max(last.end, curt.end);
}else{
result.add(last);
last = curt;
}
}
result.add(last);
return result;
}
private class IntervalComparator implements Comparator<Interval> {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
}

本文介绍了一种有效的区间合并算法,该算法能够将一系列已按起始时间排序的非重叠区间与新的区间进行合并。通过两个示例展示了如何将新区间插入到原有区间列表中并完成合并的过程。
442

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



