题目链接
贪心 + 排序
class Solution {
public int[][] merge(int[][] intervals) {
ArrayList<int[]> res = new ArrayList<>();
// 先将数组按照左区间排序
Arrays.sort(intervals, new Comparator<int[]>() {
public int compare(int[] intervals1, int[] intervals2) {
long diff = (long)intervals1[0] - (long)intervals2[0];
if (diff == 0) return 0;
return diff > 0 ? 1 : -1;
}
});
for(int i = 1; i < intervals.length; i++){
// 如果intervals[i][0] <= intervals[i - 1][1]则存在区间重叠,修改intervals[i]的左右区间
if(intervals[i][0] <= intervals[i - 1][1]){
intervals[i][0] = intervals[i - 1][0];
intervals[i][1] = Math.max(intervals[i - 1][1], intervals[i][1]);
}else{
// 不存在区间重叠,则直接添加到结果中
res.add(intervals[i - 1]);
}
}
// 将最后一个区间添加到结果
res.add(intervals[intervals.length - 1]);
// 用于将 ArrayList<ArrayList<Integer>> 转换为 int[][]
return res.toArray(new int[res.size()][]);
}
}