题意:

image.png

解题思路:

  1. 思路:[3种可能性]:O(n)
  2. 1. 如果新区间的右端点要小于区间元素的左端点,则说明无重叠,先把新区间先加入数组;
  3. 1.1 intervals = [3,4], newInterval=[1,2] =》start = 3, end = 4
  4. 1.2 arr = [1,2], start = 3, end = 4
  5. 2. 如果新区间的左端点数大于区间的右端点,则说明无重叠,先把区间数加入数组;
  6. 2.1 intervals = [3,4], newInterval=[5,6] =》start= 5, end = 6
  7. 2.2 arr = [3,4]
  8. 3. 如果跟新区间有相交,说明有重叠,则维护合并区间的最小左端点和最大右端点
  9. 3.1 intervals = [[1,3]], newInterval = [2,5]
  10. 3.2 arr = [1,5]

PHP代码实现:

  1. class Solution {
  2. function insert($intervals, $newInterval) {
  3. $ret = [];
  4. $start = $newInterval[0];
  5. $end = $newInterval[1];
  6. foreach ($intervals as $interval) {
  7. if ($interval[0] > $end) {
  8. array_push($ret, [$start, $end]);
  9. $start = $interval[0];
  10. $end = $interval[1];
  11. }
  12. if ($interval[1] < $start || $interval[0] > $end) {
  13. array_push($ret, $interval);
  14. } else {
  15. $start = min($start, $interval[0]);
  16. $end = max($end, $interval[1]);
  17. }
  18. }
  19. array_push($ret, [$start, $end]);
  20. return $ret;
  21. }
  22. }

GO代码实现:

  1. func insert(intervals [][]int, newInterval []int) [][]int {
  2. res := [][]int{}
  3. start, end, n := newInterval[0], newInterval[1], len(intervals)
  4. for i := 0; i < n; i++ {
  5. if intervals[i][0] > end {
  6. res = append(res, []int{start, end})
  7. start = intervals[i][0]
  8. end = intervals[i][1]
  9. }
  10. if intervals[i][1] < start {
  11. res = append(res, intervals[i])
  12. } else {
  13. start = Min(intervals[i][0], start)
  14. end = Max(intervals[i][1], end)
  15. }
  16. }
  17. res = append(res, []int{start, end})
  18. return res
  19. }
  20. func Max(a, b int) int {
  21. if a > b {
  22. return a
  23. }
  24. return b
  25. }
  26. func Min(a, b int) int {
  27. if a > b {
  28. return b
  29. }
  30. return a
  31. }