Skip to the content.

leetcode [57] 插入区间


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


给出一个无重叠的 ,按照区间起始端点排序的区间列表。

在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

示例 1:

输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
输出: [[1,5],[6,9]]

示例 2:

输入: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出: [[1,2],[3,10],[12,16]]
解释: 这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。
class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        left, right = 0, len(intervals) - 1
        while left < len(intervals):
            if intervals[left][1] >= newInterval[0]:
                break
            left += 1
        while right >= 0:
            if intervals[right][0] <= newInterval[1]:
                break
            right -= 1
        # append tail
        if left == len(intervals):
            return intervals + [newInterval]
        # append head
        if right == -1:
            return [newInterval] + intervals
        # append middle
        if left - right == 1:
            return intervals[:left] + [newInterval] + intervals[left:]
        # inter left
        if intervals[right][0] > newInterval[1]:
            inter = [min(newInterval[0], intervals[left][0]), max(newInterval[1], intervals[right - 1][1])]
            return intervals[:left] + [inter] + intervals[right:]
        # inter right
        elif intervals[left][1] < newInterval[0]:
            inter = [min(newInterval[0], intervals[left + 1][0]), max(newInterval[1], intervals[right][1])]
            return intervals[:left + 1] + [inter] + intervals[right + 1:]
        # inter all
        else:
            inter = [min(newInterval[0], intervals[left][0]), max(newInterval[1], intervals[right][1])]
            return intervals[:left] + [inter] + intervals[right + 1:]

来自题解:

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        # 初始状况判断
        if not newInterval:
            return intervals
        if not intervals:
            return [newInterval]
        # 已经是起点有序的了
        i = 0
        intervalsLen = len(intervals)
        while i < intervalsLen and intervals[i][1] < newInterval[0]:
            i += 1
        # 保存删除之前的位置,最后在这个位置上插入
        tempI = i
        while i < intervalsLen and intervals[i][0] <= newInterval[1]:
            newInterval[0] = min(newInterval[0], intervals[i][0])
            newInterval[1] = max(newInterval[1], intervals[i][1])
            i += 1
        else:
            del intervals[tempI:i]
            intervals.insert(tempI, newInterval)
        return intervals