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]
.
/**
* 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) {
List<Interval> result=new ArrayList<Interval>();
if(intervals==null||intervals.size()==0) {
result.add(newInterval);
return result;}
int len=intervals.size();
//sorting the intervals
Collections.sort(intervals,new Comparator<Interval>(){
@Override
public int compare(Interval o1, Interval o2){
return o1.start-o2.start;
}
});
//check two simple cases: head and tail
if(newInterval.end<intervals.get(0).start){
intervals.add(0,newInterval);
return intervals;
}
if(newInterval.start>intervals.get(len-1).end){
intervals.add(newInterval);
return intervals;
}
int flag=0;
for(int i=0;i<intervals.size();i++){
Interval temp=intervals.get(i);
//check if newInterval intersect with current interval
if((newInterval.start>=temp.start&&newInterval.start<=temp.end)||
(newInterval.end>=temp.start&&newInterval.end<=temp.end)||
newInterval.start<=temp.start&&newInterval.end>=temp.end){
//if intersect, merge interval;
if(flag==0){
flag=1;
}
newInterval.start=Math.min(newInterval.start,temp.start);
newInterval.end=Math.max(newInterval.end,temp.end);
}
else {
if(flag==1){
//if not intersect, insert the merged interval if it exist
result.add(newInterval);
result.add(temp);
flag=-1;
}else{
//no intersection, no merged interval, then just insert current interval to result
result.add(temp);
}
}
}
//if the newinterval merged with the last interval, then add newInterval to the end of the result;
if(flag==1){
result.add(newInterval);
}
if(flag==0){
//if flag is 0, this means no intersection exists between newInterval and intervals, then just find the correct position for the newInterval and then insert it.
int i=0;
while(result.get(i).start<newInterval.start&&i<result.size()){
i++;
}
result.add(i,newInterval);
}
return result;
}
}