题目描述
链接:https://leetcode-cn.com/problems/merge-intervals/
以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。
示例
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
代码
// 题解:https://leetcode-cn.com/problems/merge-intervals/solution/he-bing-qu-jian-by-leetcode-solution/
public int[][] merge(int[][] intervals) {
if (intervals == null || intervals.length <= 1) {
return intervals;
}
// 先排序
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] t0, int[] t1) {
return t0[0] - t1[0];
}
});
List<int[]> merged = new ArrayList<>();
int[] currentElements = new int[]{intervals[0][0], intervals[0][1]};
merged.add(currentElements);
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] <= currentElements[1]) {
currentElements[1] = Math.max(currentElements[1], intervals[i][1]);
} else {
int[] temp = new int[]{intervals[i][0], intervals[i][1]};
merged.add(temp);
currentElements = temp;
}
}
return merged.toArray(new int[merged.size()][]);
}