public int[][] merge(int[][] intervals) { ArrayList<int[]> res = new ArrayList<>(); if (intervals.length<2)return intervals; //重写排序规则 返回值为负则表示参数a<参数b,为正则反之
Arrays.sort(intervals, new Comparator<int[]>() { public int compare(int[] a, int[] b){ if(a[0]==b[0]){ return a[1] - b[1]; }else { return a[0] - b[0]; } } }); for (int i = 1; i < intervals.length; i++) { if (intervals[i][0]<=intervals[i-1][1]){ intervals [i][0]=intervals[i-1][0]; intervals [i][1]=Math.max(intervals[i][1],intervals[i-1][1]); intervals[i-1]= null; } } int i = 0; for (int[] a:intervals) { if (a!=null) res.add(a); } return res.toArray(new int[0][0]); }
利用list.toArray(T[] a)方法
例如:
List<double[]>转double[][]
List<double[]>list=new ArrayList<double[]>();
list.add(new double[]{10.0,12.0});
list.add(new double[]{11.0,32.0});
double[][]result=list.toArray(new double[0][0]);