原题链接:https://leetcode.com/problems/insert-interval/description/
题目描述:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
题目大意:
给出一系列已经排序好的区间,然后加入一个新的区间,要求合并这些区间
解题思路:
从前向后遍历区间,找到第一个受到新加入的区间影响的区间,对于该区间以前的区间全部直接加入结果,然后接着向后遍历找到受到新加入区间影响的最后一个区间,该区间之后的区间也是直接加入结果,而中间的区间合并成一个新的区间即可。
代码:
class Solution:
def insert(self, intervals, newInterval):
start = newInterval.start
end = newInterval.end
result = []
i = 0
while i < len(intervals):
if start <= intervals[i].end:
if end < intervals[i].start:
break
start = min(start, intervals[i].start)
end = max(end, intervals[i].end)
else:
result.append(intervals[i])
i += 1
result.append(Interval(start, end))
result += intervals[i:]
return result