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].
和56题一样,但是不是直接给的intervals,而是除了已有的排好序的intervals,还有一个新的interval,算上新的interval要求output一个不含overlap的intervals
思路:
因为已经是排好序的,不需要再额外排序了。
case 1: newInterval的起点 > intervals[i]的终点时,没有重叠,直接把intervals[i] 加入到结果。
case 2: newInterval的终点 < intervals[i]的起点时,没有重叠,这时把newInterval加入到结果,
然后把newInterval更新到当前区间
(等于借用了newInterval的空间保存当前区间,不然就要新开辟一个空间保存当前区间).
case 3: 重叠时,这时newInterval的起点要么<= interval[i]的起点,要么 > interval[i]的起点,
(因为前面已经有了newInterval的起点 > intervals[i]的终点的case,所以它肯定不会超过interval[i]的终点。同样的,newInterval的终点不会<intervals[i]的起点.)
这种情况下,只需更新newInterval的起点为二者最小,终点为二者最大,因为不能保证后面是不是还有新的重叠,所以暂时不加入到结果中。
等遍历完毕,再把最后更新的newInterval加入到结果中。
(你可能会说,最后加入的newInterval会不会已经在结果中了,会不会加重复了?注意看case 1, 虽然加入了newInterval, 但是newInterval会更新到新的区间,所以不会重复的。)
public int[][] insert(int[][] intervals, int[] newInterval) {
int n = intervals.length;
List<int[]> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
int[] tmp = intervals[i];
if(newInterval[0] > tmp[1]) {
list.add(tmp);
} else if(newInterval[1] < tmp[0]) {
list.add(newInterval);
newInterval = tmp;
}else {
newInterval[0] = Math.min(tmp[0], newInterval[0]);
newInterval[1] = Math.max(tmp[1], newInterval[1]);
}
}
list.add(newInterval);
int[][] res = new int[list.size()][2];
list.toArray(res);
return res;
}