Merge Intervals

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

# Solution

• submit code
``````class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:

if len(intervals) == 1:
return [intervals[0]]

ret = []

# 按第一个元素排序
intervals.sort(key=self.merge_sort)

# 相同起点，按终点降序
for X in range(1,len(intervals)):
if intervals[X][0] == intervals[X-1][0] and intervals[X][1] < intervals[X-1][1]:
intervals[X-1][1],intervals[X][1] = intervals[X][1],intervals[X-1][1]

left = intervals[0][0]
right = intervals[0][1]
for i in range(1,len(intervals)):
# 相交区间合并
if intervals[i][0] <= right and intervals[i][1] >= right:
right = intervals[i][1]
# 单独的/不相交区间，不合并
elif intervals[i][0] > right:
ret.append([left,right])
left = intervals[i][0]
right = intervals[i][1]
# 末尾数取值
if i == len(intervals)-1:
ret.append([left,right])

return ret

def merge_sort(self, elem):
return elem[0]
``````
• full code
``````class Solution:
def merge(self, intervals):

if len(intervals) == 1:
return [intervals[0]]

ret = []

# 按第一个元素排序
intervals.sort(key=self.merge_sort)

# 相同起点，按终点降序
for X in range(1,len(intervals)):
if intervals[X][0] == intervals[X-1][0] and intervals[X][1] < intervals[X-1][1]:
intervals[X-1][1],intervals[X][1] = intervals[X][1],intervals[X-1][1]

print(intervals)

left = intervals[0][0]
right = intervals[0][1]
print(len(intervals))
for i in range(1,len(intervals)):
print("i:",i,"left:",left,"right:",right,"intervals[i][0]",intervals[i][0],"intervals[i][1]",intervals[i][1])
# 相交区间合并
if intervals[i][0] <= right and intervals[i][1] >= right:
right = intervals[i][1]
# 单独的/不相交区间，不合并
elif intervals[i][0] > right:
ret.append([left,right])
left = intervals[i][0]
right = intervals[i][1]
# 末尾数取值
if i == len(intervals)-1:
ret.append([left,right])
print((left,right))

return ret

def merge_sort(self, elem):
return elem[0]

S = Solution()
# print(S.merge([[1,3],[2,6],[2,3],[8,10],[15,18],[17,20]]))
# print(S.merge([[1,4],[4,5]]))
# print(S.merge([[1,3],[2,6],[8,10],[15,18]]))
# print(S.merge([[1,4],[0,4]]))
# print(S.merge([[1,4]]))
print(S.merge([[1,4],[2,3]]))
``````

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

``https://www.emperinter.info/2022/04/11/merge-intervals/``

 阿里云国际版 20美元 Vultr 10美元 搬瓦工 | Bandwagon 应该有折扣吧？ Just My Socks JMS9272283 【注意手动复制去跳转】 域名 | namesilo `emperinter`(1美元) 币安 币安