Q:
You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.
Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals after the insertion.
A:
There are three cases:
1. newInterval is completely smaller than the current interval:
add the newInternal in the list and add the remaining intervals to list directly
2. newInterval overlaps the current interval:
merge this two intervals considering left boundary and right boundary and then compare this merged interval with remaining intervals.
3. newInterval is completely larger than the current interval:
add the current interval to the list.
Code:
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
if(intervals.length==0){
int[][] res = new int[1][2];
res[0] = newInterval;
return res;
}
List<int[]> list = new ArrayList<int[]>();
for(int i = 0;i<intervals.length;i++){
if(newInterval[1]<intervals[i][0]){
list.add(newInterval);
while(i<intervals.length){
list.add(intervals[i++]);
}
return list.toArray(new int[list.size()][2]);
}else if(newInterval[0]<=intervals[i][1]){
intervals[i][1] = Math.max(intervals[i][1],newInterval[1]);
intervals[i][0] = Math.min(intervals[i][0],newInterval[0]);
int j = i+1;
while(j<intervals.length){
if(intervals[j][0]<=intervals[i][1]){
intervals[i][1] = Math.max(intervals[i][1],intervals[j][1]);
j++;
}else{
break;
}
}
list.add(intervals[i]);
while(j<intervals.length){
list.add(intervals[j++]);
}
return list.toArray(new int[list.size()][2]);
}else{
list.add(intervals[i]);
}
}
list.add(newInterval);
return list.toArray(new int[list.size()][2]);
}
}