文章摘要:python怎么合并区间 python 合并区间
在python中利用遍历对区间进行合并,具体方法如下: def merge(self, intervals: […]
在python中利用遍历对区间进行合并,具体方法如下:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
result = []
intervals.sort()
while intervals:
mid = intervals[0]
cur1 = 0
cur2 = 0
for i, x in enumerate(intervals[1:], 1):
if mid[1] >= x[0]:
mid[1] = max(x[1], mid[1])
cur1 = i
else:
cur2 = i
break
result.append(mid)
intervals = intervals[max(cur1+1, cur2):]
return result