以数组 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 {
public int[][] merge(int[][] intervals) {
int n = intervals.length;
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
int start = intervals[0][0], end = intervals[0][1];
List<int[]> list = new ArrayList<>();
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;
}
}