image.png

解题思路

排序

image.png

code

  1. public int[][] merge(int[][] intervals) {
  2. List<int[]> res = new ArrayList<>();
  3. if (intervals == null || intervals.length == 0) return res.toArray(new int[0][]);
  4. Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
  5. int i = 0;
  6. while (i < intervals.length) {
  7. int left = intervals[i][0];
  8. int right = intervals[i][1];
  9. while (i < intervals.length - 1 && intervals[i + 1][0] <= right) {
  10. i++;
  11. right = Math.max(right, intervals[i][1]);
  12. }
  13. res.add(new int[]{left, right});
  14. i++;
  15. }
  16. return res.toArray(new int[0][]);
  17. }