> For the complete documentation index, see [llms.txt](https://imhuay.gitbook.io/studies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/niu-ke-0037-zhong-deng-he-bing-qu-jian.md).

# 合并区间

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E4%B8%AD%E7%AD%89\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/pages/R5NyOzkn3qAZy7wCx1pS#中等) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E6%8E%92%E5%BA%8F\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/02/pages/R5NyOzkn3qAZy7wCx1pS#排序)

**问题简述**

```
给出一组区间，请合并所有重叠的区间。
请保证合并后的区间按区间起点升序排列。
```

> [合并区间\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a)

**思路**

* 按开始节点排序，则可以合并的部分必是连续的，然后根据题意模拟即可；

<details>

<summary><strong>Python</strong></summary>

```python
# class Interval:
#     def __init__(self, a=0, b=0):
#         self.start = a
#         self.end = b
#
# 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
# 
# @param intervals Interval类一维数组 
# @return Interval类一维数组
#
class Solution:
    def merge(self , intervals: List[Interval]) -> List[Interval]:
        # write code here
        if not intervals: return []
        
        a = sorted(intervals, key=lambda x: (x.start, x.end))
        ret = [a[0]]
        for it in a[1:]:
            pre = ret[-1]
            if it.start > pre.end:
                ret.append(it)
            else:
                pre.end = max(pre.end, it.end)
        
        return ret
```

</details>
