# 插入区间

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

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

 

示例 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] 重叠。

示例 3:

输入:intervals = [], newInterval = [5,7]
输出:
[[5,7]]

示例 4:

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

示例 5:

输入:intervals = [[1,5]], newInterval = [2,7]
输出:
[[1,7]]

 

提示:

## template ```python class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def list2interval(self, list_interval): ret = [] for i in list_interval: interval = Interval(i[0], i[1]) ret.append(interval) return ret def interval2list(self, interval): ret = [] x = [0,0] for i in interval: x[0] = i.start x[1] = i.end ret.append(x) x = [0,0] return ret def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ if intervals is None or len(intervals) == 0: return [newInterval] intervals = self.list2interval(intervals) newInterval = Interval(newInterval[0], newInterval[1]) intervals.sort(key=lambda x:x.start) pos = 0 while pos < len(intervals): if newInterval.end < intervals[pos].start: intervals.insert(pos, newInterval) intervals = self.interval2list(intervals) return intervals if self.check_overlap(intervals[pos], newInterval): temp = intervals.pop(pos) newInterval = self.merge_intervals(temp, newInterval) else: pos += 1 if len(intervals) == 0 or pos == len(intervals): intervals.append(newInterval) intervals = self.interval2list(intervals) return intervals def check_overlap(self, curr_int, new_int): if curr_int.start <= new_int.start: if curr_int.end > new_int.start: return True else: if curr_int.start <= new_int.end: return True return False def merge_intervals(self, int1, int2): temp_int = Interval() temp_int.start = min([int1.start, int2.start]) temp_int.end = max([int1.end, int2.end]) return temp_int # %% s = Solution() print(s.insert(intervals = [[1,3],[6,9]], newInterval = [2,5])) ``` ## 答案 ```python ``` ## 选项 ### A ```python ``` ### B ```python ``` ### C ```python ```