在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