自己的做法
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
mystack=[]
flag=0
for a in intervals:
if flag==0:
if a.start>newInterval.start:
mystack.append(newInterval)
flag=1
while len(mystack)> 1 and mystack[-1].start <= mystack[-2].end:
new=Interval(mystack[-2].start,max(mystack[-2].end,mystack[-1].end))
mystack.pop()
mystack.pop()
mystack.append(new)
mystack.append(a)
if flag==1:
if len(mystack)> 1 and mystack[-1].start > mystack[-2].end:
flag=2
while len(mystack)> 1 and mystack[-1].start <= mystack[-2].end:
new=Interval(mystack[-2].start,max(mystack[-2].end,mystack[-1].end))
mystack.pop()
mystack.pop()
mystack.append(new)
if flag==0:
mystack.append(newInterval)
while len(mystack)> 1 and mystack[-1].start <= mystack[-2].end:
new=Interval(mystack[-2].start,max(mystack[-2].end,mystack[-1].end))
mystack.pop()
mystack.pop()
mystack.append(new)
return mystack
别人简洁的代码
class Solution:
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
start,end=newInterval.start,newInterval.end
left,right=[],[]
for i in range(len(intervals)):
if intervals[i].end<start:
left.append(intervals[i])
elif intervals[i].start>end:
right.append(intervals[i])
if len(left)+len(right)!=len(intervals):
start=min(intervals[len(left)].start,start)
end=max(intervals[-len(right)-1].end,end)
return left+[Interval(start,end)]+right