Problem Description:
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Analysis:
首先对这个二维数组进行排序,可以看成是一组点的二维数组,然后按照x轴从小到大的序列进行排序。然后再一次比较数组中每行的值,如果有重合的就进行合并,如何没有重合就放入到数组中。
Code:
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
if(o1[0] == o2[0]) {
return o1[1] - o2[1];
} else {
return o1[0] - o2[0];
}
}
});
// for(int i = 0; i< intervals.length; i++) {
// System.out.println(intervals[i][0] + ", " + intervals[i][1]);
// }
if(intervals.length < 1)
return new int[0][0];
int i = 0;
int j = 1;
int k = 1;
while( i + j < intervals.length) {
if(intervals[i][1] < intervals[i + j][0]) {
k++;
intervals[i + 1] = intervals[i + j];
i++;
j = 1;
} else {
intervals[i][1] = Math.max(intervals[i][1], intervals[i + j][1]);
j++;
}
}
int[][] res = new int[k][2];
System.arraycopy(intervals, 0, res, 0, k);
return res;
}
}