LeetCode每日一题—57.插入区间
题目描述
给出一个无重叠的 ,按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
示例 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] 重叠。
题目分析
我们创建一个空的数组result=[ ]
这就是我们最后返回的值。接下来,我么需要确定如何循环遍历数组可以得到满足的结果。
我确定一个while循环在最外面用来推进,当满足后一个数组的前一个元素在前一个数组的区间之中时,这个时候就需要进行合并了,但同时,万一再后面的数组也可以进行合并,这个时候我们就需要再进行一个循环,这样将可以合并的一起合并(要是说的不清楚,可以参考下面的代码哦,理科生的痛)。
问题解决
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
intervals.append(newInterval)
intervals.sort()
result=[]
n=len(intervals)
i=0
while i<n:
first=intervals[i][0]
last=intervals[i][1]
while i<n-1 and intervals[i+1][0]<=last:
i+=1
last=max(last,intervals[i][1])
result.append([first,last])
i+=1
return result