题目
给出一个无重叠的 ,按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
示例 1:
输入:intervals = [[1,3],[6,9]], newInterval = [2,5]
输出:[[1,5],[6,9]]
示例 2:
输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出:[[1,2],[3,10],[12,16]]
解释:这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。
解题思路
Insert + Merge
Like 56. 合并区间, firstly use binary search to find the insert index, then insert, then merge. Time complexity for binary search is o ( log n ) o(\log n) o(logn), for merge is o ( n ) o(n) o(n).
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
Merge
Instead of using binary search to find the insert index, we could start by iterate from left to right.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
Merge2
Keep those intervals that are at the left of the new interval, and those that are at the right of the new interval. Then merge those overlapped.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
n
)
o(n)
o(n)
代码
Insert + Merge
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
start_indexs = list(item[0] for item in intervals)
insert_index = bisect.bisect_left(start_indexs, newInterval[0])
intervals.insert(insert_index, newInterval)
# merge intervals
prev_start, prev_end = intervals[0]
res = []
for start, end in intervals[1:]:
if prev_end >= start:
prev_end = max(prev_end, end)
else:
res.append([prev_start, prev_end])
prev_start, prev_end = start, end
res.append([prev_start, prev_end])
return res
Merge
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
i = 0
while i < len(intervals) and intervals[i][1] < newInterval[0]:
res.append(intervals[i])
i += 1
while i < len(intervals) and newInterval[1] >= intervals[i][0]:
newInterval = [min(intervals[i][0], newInterval[0]), max(intervals[i][1], newInterval[1])]
i += 1
res.append(newInterval)
return res + intervals[i:]
Merge2
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
left, right = [], []
new_start, new_end = newInterval
for i in intervals:
if i[1] < new_start:
left.append(i)
elif i[0] > new_end:
right.append(i)
else:
new_start = min(i[0], new_start)
new_end = max(i[1], new_end)
return left + [[new_start, new_end]] + right