思路
将二维数组按照第一列升序排列,把intervals[0][0]作为第一个区间的起点,将
intervals[0][1]和intervals[1][0]进行比较,如果intervals[0][1]<intervals[1][0],则不能合并,否则可以合并,将Math.max(intervals[position][1],intervals[position+1][1])作为临时右端点,依次类推
解题过程
注意: 要写为list.add(new ArrayList§),如果list.add§这样,p.clear()会清空数据
Code
class Solution {public List<List<Integer>> list=new ArrayList<>();public int row;public int[][] merge(int[][] intervals) {Arrays.sort(intervals,(a,b)->a[0]-b[0]);//二维数组中每行数组中的第一个数按从小到大的顺序进行排列row=intervals.length;List<Integer> p=new ArrayList<>();p.add(intervals[0][0]);method(p,0,intervals);int ans[][]=listTo2DArray(list);return ans;}public void method(List<Integer> p,int position,int[][] intervals){if(position+1==row){ //最后一行p.add(intervals[position][1]);list.add(p);}else{if(intervals[position][1]>=intervals[position+1][0]){intervals[position+1][1]=Math.max(intervals[position][1],intervals[position+1][1]);method(p,position+1,intervals);}else{p.add(intervals[position][1]);list.add(new ArrayList(p));p.clear();p.add(intervals[position+1][0]);method(p,position+1,intervals);}}}public static int[][] listTo2DArray(List<List<Integer>> listOfLists) {int rows = listOfLists.size();int cols = 0;for (List<Integer> list : listOfLists) {cols = Math.max(cols, list.size()); // 获取最大列数}int[][] twoDimArray = new int[rows][cols];for (int i = 0; i < rows; i++) {List<Integer> rowList = listOfLists.get(i);for (int j = 0; j < rowList.size(); j++) {twoDimArray[i][j] = rowList.get(j);}}return twoDimArray;}
}作者:菜卷
链接:https://leetcode.cn/problems/merge-intervals/solutions/2893781/he-bing-qu-jian-by-ashi-jian-chong-dan-l-0mr3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。