
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
res = []
start, end = newInterval[0], newInterval[1]
n = len(intervals)
i = 0
# all intvls that end before newInterval starts
while i < n and intervals[i][1] < start:
res.append(intervals[i])
i += 1
# merge overlapping
while i < n and intervals[i][0] <= end:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
res.append(newInterval)
# add all rest
while i < n:
res.append(intervals[i])
i += 1
return res
class Solution(object):
def insert(self, intervals, newInterval):
res = []
if not intervals:
res.append(newInterval)
return res
curS, curE = newInterval[0], newInterval[1]
for interval in intervals:
lastS, lastE = interval[0], interval[1]
if lastS > curE:
res.append([curS, curE])
curS, curE = lastS, lastE
elif lastE < curS:
res.append(interval)
else:
curS, curE = min(lastS, curS), max(curE, lastE)
res.append([curS, curE])
return res