Insert Interval
虽然现在看算法很简单,但是实现比较tricky,另外算法背后的逻辑比较不容易想。
记忆要点:
- 因为interval list已经是排好序的了,核心就是顺序比较当前的interval和newInterval。主要分成两种情况:newInterval可以直接插入或者不确定。对于前者,就是newInterval.end<interval.start
- 这题不是in-place的,因为没法确定要删除的interval的个数
- 过程就是问下一个要push的interval是哪个?newInterval or next in intervals or overlapping
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
i=0
res = []
while i<len(intervals):
if intervals[i].start>newInterval.end:
res.append(newInterval)
res+=intervals[i:]
return res
elif newInterval.start>intervals[i].end:
res.append(intervals[i])
i+=1
else:
newInterval.start=min(newInterval.start, intervals[i].start)
newInterval.end=max(newInterval.end, intervals[i].end)
i+=1
res.append(newInterval)
return res