合并区间
https://leetcode.cn/problems/merge-intervals/description/?envType=study-plan-v2&envId=top-interview-150
这题思维量一般但比较考察API的使用。
1、数组的自定义排序
2、数组的初始化定义
3、Arrays转int
通过重写Comparator的compare方法来自定义排序规则,返回的值看正负。
Arrays.sort(intervals,new Comparator<int[]>(){public int compare(int[] a,int[] b){return a[0]-b[0];}
});
class Solution {public int[][] merge(int[][] intervals) {Arrays.sort(intervals,new Comparator<int[]>(){public int compare(int[] a,int[] b){return a[0]-b[0];}});List<int[]> merge = new ArrayList<>();merge.add(intervals[0]);for(int i=1;i<intervals.length;i++){int left = intervals[i][0];int right = intervals[i][1];int merge_left = merge.get(merge.size()-1)[0];int merge_right = merge.get(merge.size()-1)[1];if(left>=merge_left&&left<=merge_right){int[] temp = {merge_left,Math.max(right,merge_right)};merge.set(merge.size()-1,temp);}else{merge.add(intervals[i]);}} //再转化成数组return merge.toArray(new int[merge.size()][]);}
}