以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。
示例 1:
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
提示:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
class Solution {
//先按照intervals[i][0]从小到大排序,然后遍历数组,维护start,end变量,当当前a <= end && b <= end 说明[1,4],[2,3]这种,直接跳过,当a <= end,[1,4],[3,5],将end更新成b就行,否则则将start,end加入答案,然后更新start,end,注意最后将start,end加入答案
public int[][] merge(int[][] intervals) {
int n = intervals.length;
Arrays.sort(intervals, (a,b) -> a[0] - b[0]);
List<int[]> list = new ArrayList<>();
int start = intervals[0][0], end = intervals[0][1];
for (int i = 1; i < n; ++i) {
int a = intervals[i][0], b = intervals[i][1];
if (a <= end && b <= end) continue;
else if (a <= end) end = b;
else {
list.add(new int[]{start, end});
start = a;
end = b;
}
}
list.add(new int[]{start, end});
int[][] res = new int[list.size()][2];
for (int i = 0; i < list.size(); ++i) {
res[i][0] = list.get(i)[0];
res[i][1] = list.get(i)[1];
}
return res;
}
}