https://leetcode.com/problems/insert-interval/description/
将所给区间插入连续不交叠区间序列,若交叠则合并
思路:先找交叠的起始,再找交叠的终止。注意处理边界情况
至于为何要在第二次while中每次更新?因为插入段与原序列的元素区间可能存在包含关系,这样可以避免遗漏
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
res = []
n = len(intervals)
if n == 0: #序列为空,直接插入
res.append(newInterval)
return res
i = 0 #从头开始找交叠的起点位置
while i < n and intervals[i].end < newInterval.start:
res.append(intervals[i])
i += 1
#找终点,每次更新
while i < n and intervals[i].start <= newInterval.end:
newInterval = Interval(min(newInterval.start, intervals[i].start),
max(newInterval.end, intervals[i].end))
i += 1
res.append(newInterval) #将合并后的交叠段插入
#若后面还有,直接插入
while i < n:
res.append(intervals[i])
i += 1
return res