---
title: leetcode-merge-intervals
date: 2020-04-16 19:22:26
tags:
categories: leetcode
---


### 56. 合并区间



[题目](https://leetcode-cn.com/problems/merge-intervals/)



<!--more-->



首先将区间按起点由小到大排序，这样相邻的两个就能通过终点判断是否重合。



```python
class Solution:
  def merge(self, intervals):
    if not intervals:
      return []
    intervals.sort()
    merged = []
    l = len(intervals)
    m = intervals[0]
    for x in range(l-1):
      j = intervals[x+1]
      if m[1] >= j[0]:
        if m[1] <= j[1]:
          m = [m[0], j[1]]
        else:
          continue
      else:
        merged.append(m)
        m = j
    if m:
      merged.append(m)
    return merged
```



