贪心,将 newInterval 加入到 Intervals 然后对其排序,用栈做存储;依次遍历 Intervals,对比栈顶元素,最终返回栈
# class Interval:
# def __init__(self, a=0, b=0):
# self.start = a
# self.end = b
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param Intervals Interval类一维数组
# @param newInterval Interval类
# @return Interval类一维数组
#
class Solution:
def insertInterval(self , Intervals: List[Interval], newInterval: Interval) -> List[Interval]:
# write code here
Intervals.append(newInterval)
Intervals.sort(key=lambda x:x.start)
stack = [Intervals[0]]
for inter in Intervals[1:]:
if inter.start <= stack[-1].end:
t = stack.pop()
stack.append(Interval(min(inter.start, t.start), max(inter.end, t.end)))
else:
stack.append(inter)
return stack