56. 合并区间
题目描述
题解
详细请看代码
class Solution {
public int[][] merge(int[][] intervals) {
int n = intervals.length;
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
List<int[]> merge = new ArrayList<int[]>();
for (int i = 0; i < n; i++) {
int left = intervals[i][0];
int right = intervals[i][1];
if (merge.size() == 0 || merge.get(merge.size() - 1)[1] < left) {
merge.add(new int[]{left, right});
}
else {
merge.get(merge.size() - 1)[1] = Math.max(merge.get(merge.size() - 1)[1], right);
}
}
return merge.toArray(new int[merge.size()][]);
}
}
|