package com.zmz.algorithm.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author 张明泽
* Create by 2022/5/24 9:47
* 合并区间
* LeetCode-56
*/
public class MergeRange {
public static void main(String[] args) {
int[][] arr = {{8,10},{2,6},{1,3},{15,18}};
arr = merge(arr);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println(" ");
}
}
public static int[][] merge(int[][] arr) {
Arrays.sort(arr, (a,b) -> a[0] - b[0]);
List<int[]> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
int left = arr[i][0];
int right = arr[i][1];
// 第一次 或 无重叠
if(list.size() == 0 || list.get(list.size() - 1)[1] < left) {
list.add(new int[]{left,right});
} else {
list.get(list.size() - 1)[1] = Math.max(list.get(list.size() - 1)[1],right);
}
}
return list.toArray(new int[list.size()][]);
}
}
最后修改:2022 年 05 月 25 日 12 : 18 PM
© 允许规范转载