1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int[][] merge(int[][] intervals) {
if (intervals.length <= 1) return intervals;

Arrays.sort(intervals, new Comparator<int[]>(){
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
List<int[]> res = new ArrayList<>();
res.add(intervals[0]);

for (int[] i : intervals) {
if (res.get(res.size() - 1)[1] < i[0]) res.add(i);
else {
res.get(res.size() - 1)[1] = Math.max(res.get(res.size()-1)[1], i[1]);
}
}

return res.toArray(new int[res.size()][2]);
}
  • ArrayList to Array: someArrayList.toArray()
  • Object[] toArray(): 直接调用返回的是Object[]类型的array, 一般都不这样用
  • <T> T[] toArray(T[] a): a: the array into which all elements of list are to be stored, if it is big enough; otherwise, a new arrya of the same type is allocated for this purpose.