57. Insert Interval
# Medium
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
cur = 0
n = len(intervals)
# add all non-overlap intervals into res
while cur < n and intervals[cur][1] < newInterval[0]:
res.append(intervals[cur][:])
cur += 1
# find the new interval
while cur < n and newInterval[1] >= intervals[cur][0]:
newInterval[0] = min(intervals[cur][0], newInterval[0])
newInterval[1] = max(intervals[cur][1], newInterval[1])
cur += 1
res.append(newInterval[:])
while cur < n:
res.append(intervals[cur][:])
cur += 1
return res
Last updated
Was this helpful?