链接: 插入区间
给你一个 无重叠的,按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
示例 1:
输入:intervals = [[1,3],[6,9]], newInterval = [2,5]
输出:[[1,5],[6,9]]
示例 2:
输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出:[[1,2],[3,10],[12,16]]
解释:这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。
示例 3:
输入:intervals = [], newInterval = [5,7]
输出:[[5,7]]
示例 4:
输入:intervals = [[1,5]], newInterval = [2,3]
输出:[[1,5]]
示例 5:
输入:intervals = [[1,5]], newInterval = [2,7]
输出:[[1,7]]
提示:
0 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= intervals[i][0] <= intervals[i][1] <= 10^5
intervals
根据 intervals[i][0]
按 升序 排列newInterval.length == 2
0 <= newInterval[0] <= newInterval[1] <= 10^5
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> list = new ArrayList<>();
boolean isAdded = false;
int start = -1;
for (int i = 0; i < intervals.length; i++) {
// 不在新区间范围内
boolean beyond = newInterval[0] > intervals[i][1] || newInterval[1] < intervals[i][0];
if (beyond) {
if (newInterval[1] < intervals[i][0] && !isAdded) {
isAdded = true;
start = start == -1 ? newInterval[0] : start;
list.add(new int[]{start, newInterval[1]});
start = -1;
}
list.add(intervals[i]);
continue;
}
// 在新区间范围内
boolean containStart = newInterval[0] >= intervals[i][0] && newInterval[0] <= intervals[i][1];
boolean containEnd = newInterval[1] >= intervals[i][0] && newInterval[1] <= intervals[i][1];
if (containStart && containEnd) {
isAdded = true;
list.add(intervals[i]);
} else if (containStart) {
start = Math.min(intervals[i][0], newInterval[0]);
} else if (containEnd) {
int end = Math.max(intervals[i][1], newInterval[1]);
if (start != -1) {
isAdded = true;
list.add(new int[]{start, end});
} else {
isAdded = true;
list.add(new int[]{newInterval[0], end});
}
start = -1;
}
}
if (start != -1) {
list.add(new int[]{start, newInterval[1]});
}
if (list.size() == 0 || list.get(list.size() - 1)[1] < newInterval[0]) {
list.add(newInterval);
} else if (list.get(0)[0] > newInterval[1]) {
list.add(0, newInterval);
}
return list.toArray(new int[list.size()][2]);
}
}
整理完毕,完结撒花~