LeetCode 56. [Python] Insert Intervals
原题链接
中等
作者:
徐辰潇
,
2021-05-05 22:46:57
,
所有人可见
,
阅读 311
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
#TC : O(len(intervals))
#SC: O(1)
res = []
flag = 0
i = 0
while i < len(intervals):
if intervals[i][1] < newInterval[0]:
res.append(intervals[i])
i += 1
else:
if intervals[i][0] > newInterval[1]:
if flag == 0:
res.append(newInterval)
res.append(intervals[i])
flag = 1
else:
res.append(intervals[i])
i += 1
else:
#when two intervals are intersecting, update newInterval
newInterval[0] = min(intervals[i][0], newInterval[0])
newInterval[1] = max(intervals[i][1], newInterval[1])
i += 1
if flag == 0:
res.append(newInterval)
return res