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]
.
思路分析:这题题目本身并不难,但是还是调试了很久。定义结果res容器,首先将newInterval的start和intervals里面区间的end比较,找到应该插入newInterval的位置,插入newInterval有点讲究,应该先添加newInterval(添加前可能需要更新其start)到res,然后继续将后检查,看添加的newInterval是否还与后面的区间有冲突,如果有冲突,再更新newInterval的end一个一个合并后面的可以merge的区间(条件是newInterval.end >= intervals.get(i).start)。在java里面,List容器里面保存的是对象newInterval的引用(地址),所以,对newInterval的修改也相当于对res的修改。这样向后检查一直到merge完所有可以merge的区间,最后添加剩下的区间到res即可。时间复杂度和空间复杂度都是O(N)。实现的时候,可以用一个指针i从头到尾遍历intervals到底,针对不同的段进行不同处理。这题和LeetCode Merge Intervals有关系,可以联系起来思考。
AC Code
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
//1120
List<Interval> res = new ArrayList<Interval>();
if(intervals.size() == 0) {
res.add(newInterval);
return res;
}
int i = 0;
while(i < intervals.size() && newInterval.start > intervals.get(i).end){
res.add(intervals.get(i));
i++;
}
if(i < intervals.size())
newInterval.start = Math.min(newInterval.start, intervals.get(i).start);
res.add(newInterval);
//first add newInterval, then use newInterval to merge the afterwards intervals that within the range
//Since we mantain reference of newInterval in res, the modification of newInterval also modify res
//merge afterwards intervals one by one
while(i < intervals.size() && newInterval.end >= intervals.get(i).start){
newInterval.end = Math.max(newInterval.end, intervals.get(i).end);
i++;
}
for(int j = i; j < intervals.size(); j++){
res.add(intervals.get(j));
}
return res;
//1139
}
}