python

python怎么合并区间

养鱼的猫咪
523
2021-03-08 12:09:45
栏目: 编程语言

python怎么合并区间

在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

0
看了该问题的人还看了