题目描述:
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].
这个题不难,关键是要考虑周到,每一种情况都要想清楚。leetcode上对于不会通过的case都会有错误提示,但是很多公司招聘的oj平台是不会给错误提示的,所以大家要试着不去看错误提示,加油吧。
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> list=new ArrayList<Interval>();
int n=intervals.size();
if(n==0){
list.add(newInterval);
}
boolean go=false;
for (int i = 0; i < n; i++) {
if(go){
list.add(intervals.get(i));break;
}
if(intervals.get(i).end<newInterval.start){
list.add(intervals.get(i));
//当newInterval是最后一个的时候,要直接插入
if(i==n-1){
list.add(newInterval);
}
}else if(intervals.get(i).start>newInterval.end){
list.add(intervals.get(i));
list.add(newInterval);
go=true;
}else{
newInterval.start=newInterval.start<intervals.get(i).start?newInterval.start:intervals.get(i).start;
newInterval.end=newInterval.end>intervals.get(i).end?newInterval.end:intervals.get(i).end;
//当newInterval是最后一个的时候,要直接插入
if(i==n-1){
list.add(newInterval);
}
}
}
return list;
}