题目
基本思路
首先,将newInterval添加到intervals中,然后按照区间开始数值,进行排序,最后将对于是否需要merge进行判断,分情况处理
花费了额外的存储空间
实现代码
# 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]
"""
intervals.append(newInterval)
intervals.sort(key=lambda x:x.start)
length = len(intervals)
res = []
for i in range(length):
if res == []:
res.append(intervals[i])
else:
if res[-1].start <= intervals[i].start <= res[-1].end:
res[-1].end = max(intervals[i].end,res[-1].end)
else:
res.append(intervals[i])
return res