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:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals =[[1,2],[3,5],[6,7],[8,10],[12,16]]
, newInterval =[4,8]
Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval[4,8]
overlaps with[3,5],[6,7],[8,10]
.
要解这种题,首先要迅速对可能出现的情况进行分类,比如这道题可以分三类:
聪明的分类,对吧。然后中心思想是:
当当前的interval的end小于newInterval的start时,说明新的区间在当前遍历到的区间的后面,并且没有重叠,这意味着永远都和这个interval无关,所以res添加当前的interval;
当当前的interval的start大于newInterval的end时,说明新的区间比当前遍历到的区间要前面,并且也没有重叠,所以把newInterval添加到res里,和上面的原因类似,并更新newInterval为当前的interval,因为之后只有大的interval才能用上。
当当前的interval与newInterval有重叠时,merge interval并更新新的newInterval为merge后的。大大,小小
class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { List<int[]> resu = new ArrayList(); int s = newInterval[0], e = newInterval[1]; int i = 0; //add all intervals which are before the new Interval while(i < intervals.length && intervals[i][1] < s){ resu.add(intervals[i++]); } //ensure all of the intervals are merged based on the start and end time of the newInterval while(i < intervals.length && intervals[i][0] <= e){ s = Math.min(s, intervals[i][0]); e = Math.max(e, intervals[i][1]); i++; } //Add merged interval resu.add(new int[]{s, e}); //Add the remaining intervals while(i < intervals.length) resu.add(intervals[i++]); int j = 0; int[][] res = new int[resu.size()][2]; for(int[] tmp: resu){ res[j++] = tmp; } return res; } }