leetcode 56. 合并区间

解题思路

遍历数组,比较元素区间即可

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
ret = []
new_intervals = sorted(intervals, key=lambda x: x[0])
left, right = new_intervals[0]

for a, b in new_intervals[1:]:
if right >= b:
continue

if right >= a:
right = b
else:
ret.append([left, right])
left = a
right = b

ret.append([left, right])
return ret