题意:

image.png

解题思路:

  1. 思路:
  2. 1. 先按首位置进行排序[intervals[i][0]];
  3. 2. 如何判断两个区间是否重叠 a = [1,3],b = [2,6]
  4. 3. b[0] <= a[1], 2 < 3 说明两个区间有重叠.
  5. 4. 那么区间就是 [a[0], max(a[1], b[1])],所以区间为:[1,6]

PHP代码实现:

  1. class Solution {
  2. function merge($intervals) {
  3. if (count($intervals) < 1) return [];
  4. $intervals = $this->arraySort($intervals);
  5. $j = 0;
  6. $ans[$j] = $intervals[0];
  7. for ($i = 1; $i < count($intervals); $i++) {
  8. $start = $intervals[$i][0];
  9. $end = $intervals[$i][1];
  10. if ($start <= $ans[$j][1]) {
  11. $ans[$j] = [$ans[$j][0], max($ans[$j][1], $end)];
  12. } else {
  13. $j++;
  14. $ans[$j] = $intervals[$i];
  15. }
  16. }
  17. return $ans;
  18. }
  19. function arraySort($intervals) {
  20. $startArray = [];
  21. foreach ($intervals as $interval) {
  22. $startArray[] = $interval[0];
  23. }
  24. array_multisort($startArray, SORT_ASC, $intervals);
  25. return $intervals;
  26. }
  27. }

GO代码实现:

  1. func merge(intervals [][]int) [][]int {
  2. if len(intervals) <= 1 {
  3. return intervals
  4. }
  5. sort.Slice(intervals, func(i, j int) bool {
  6. return intervals[i][0] < intervals[j][0]
  7. })
  8. res := make([][]int, 0)
  9. start := intervals[0][0]
  10. end := intervals[0][1]
  11. for i := 1; i < len(intervals); i++ {
  12. if end < intervals[i][0] {
  13. res = append(res, []int{start, end})
  14. start = intervals[i][0]
  15. end = intervals[i][1]
  16. } else {
  17. end = max(end, intervals[i][1])
  18. }
  19. }
  20. res = append(res, []int{start, end})
  21. return res
  22. }
  23. func max(a, b int) int {
  24. if a > b {
  25. return a
  26. }
  27. return b
  28. }