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].
Subscribe to see which companies asked this question.
这是要实现区间的并集,思路是,遍历已经存在的区间,当新区间end<遍历元素的start,遍历结束,其余的有如下几种情况:1,新区间的start在当前的区间之间,但是end在当前元素后面,则将新区间的start=当前元素的start;2,新区间的end在当前区间内,但是start在区间前面,则将新区间end=当前区间的end;3,当前区间包括新区间,则令新区间=当前区间;4,新区间包括当前区间,则进行下一个区间的比较。当跳出循环之后,将新区间放入list中,还有原list中没有比较的区间。具体代码如下:
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
ArrayList<Interval>newIntervals=new ArrayList<>();
int i=0;
for (; i < intervals.size(); i++) {
Interval interval=intervals.get(i);
if (interval.start>newInterval.end) break;
if (newInterval.start>=interval.start&&newInterval.start<=interval.end&&newInterval.end>interval.end)
newInterval.start=interval.start;
if (newInterval.start<interval.start&&newInterval.end>=interval.start&&newInterval.end<=interval.end)
newInterval.end=interval.end;
if (newInterval.start>=interval.start&&newInterval.end<=interval.end){
newInterval.start=interval.start;
newInterval.end=interval.end;
}
if (newInterval.start<=interval.start&&newInterval.end>=interval.end) continue;
if (newInterval.start>interval.end) newIntervals.add(interval);
}
newIntervals.add(newInterval);
for (; i < intervals.size(); i++) {
newIntervals.add(intervals.get(i));
}
return newIntervals;
}