一、题目
二、思路
遍历所有区间,先找和插入区间不重叠的左边区间,条件是当前区间右边的值小于插入区间左边的值,再找和插入区间重叠的中间区间,条件是当前区间的左边的值小于等于插入区间右边的值,新插入区间左边的值是当前区间和插入区间左边较小的值,新插入区间右边的值是当前区间和插入区间右边较大的值,剩下的区间就是和插入区间不重叠的右边区间
三、代码实现
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> res = new ArrayList<>();
int i = 0, length = intervals.length;
//不重叠的左边区间,当前区间的右边比插入区间的左边小
while (i < length && intervals[i][1] < newInterval[0]) {
res.add(intervals[i]);
i++;
}
//重叠部分的中间区间,当前区间的左边小于等于插入区间的右边
while (i < length && intervals[i][0] <= newInterval[1]) {
//左边取当前区间左边和插入区间左边的较小值
newInterval[0] = Math.min(newInterval[0],intervals[i][0]);
//右边取当前区间右边和插入区间右边的较大值
newInterval[1] = Math.max(newInterval[1],intervals[i][1]);
i++;
}
res.add(newInterval);
//不重叠的右边区间
while (i < length) {
res.add(intervals[i]);
i++;
}
return res.toArray(new int[0][]);
}