主要学习下Arrays.sort()排序二维数组。
class Solution { public int[][] merge(int[][] intervals) { Arrays.sort(intervals, new Comparator<int[]>() { //先按第一维进行排序 @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); int newIntervals[][] = new int[intervals.length][2]; int index = 0; newIntervals[0][0] = intervals[0][0]; newIntervals[0][1] = intervals[0][1]; for (int i = 1; i < intervals.length; i++) { if(intervals[i][0]>newIntervals[index][1]){ index ++; newIntervals[index][0] = intervals[i][0]; newIntervals[index][1] = intervals[i][1]; } else if(intervals[i][0]<=newIntervals[index][1] && intervals[i][1]>=newIntervals[index][1]){ newIntervals[index][1] = intervals[i][1]; }else{ continue; } } int array[][]= new int[index+1][2]; for (int i = 0; i <=index ; i++) { array[i][0] = newIntervals[i][0]; array[i][1] = newIntervals[i][1]; } return array; } }