classSolution{publicint[][]merge(int[][] intervals){// 1.数据结构Arrays.sort(intervals,(o1,o2)->Integer.compare(o1[0],o2[0]));List<int[]> res =newArrayList<>();// left 和 rightint left = intervals[0][0];int right = intervals[0][1];// 2. 遍历for(int i =1; i < intervals.length;i++){// 2.1 不重叠if(intervals[i][0]>right){
res.add(newint[]{left,right});
left = intervals[i][0];
right = intervals[i][1];}else{
right =Math.max(right,intervals[i][1]);}}
res.add(newint[]{left,right});return res.toArray(newint[res.size()][]);}}
3- ACM 实现
publicclass mergeIntervals {publicstaticint[][]merge(int[][] intervals){// 1. 排序Arrays.sort(intervals,(o1,o2)->Integer.compare(o1[0],o2[0]));// 2.数据结构List<int[]> res =newArrayList<>();int left = intervals[0][0];int right = intervals[0][1];// 3.遍历for(int i =1; i < intervals.length;i++){// 覆盖if(intervals[i][0]>right){
res.add(newint[]{left,right});
left = intervals[i][0];
right = intervals[i][1];}else{
right =Math.max(right,intervals[i][1]);}}// 4. 结果
res.add(newint[]{left,right});return res.toArray(newint[res.size()][]);}publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);System.out.println("输入二维数组个数");int n = sc.nextInt();int[][] intervals =newint[n][2];for(int i =0; i < n ; i++){
intervals[i][0]= sc.nextInt();
intervals[i][1]= sc.nextInt();}int[][] res =merge(intervals);for(int[] r:res){System.out.print("["+ r[0]+", "+ r[1]+"]");}}}