> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/google/56-merge-intervals.md).

# 56 Merge Intervals

## 56. [Merge Intervals](https://leetcode.com/problems/merge-intervals/description/)

## 1. Question

Given a collection of intervals, merge all overlapping intervals.

For example,\
Given`[1,3],[2,6],[8,10],[15,18]`,\
return`[1,6],[8,10],[15,18]`.

## 2. Implementation

**(1) Scan Line**

```java
/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> res = new ArrayList<>();

        if (intervals == null || intervals.size() == 0) {
            return res;
        }

        Collections.sort(intervals, new Comparator<Interval>() {
            @Override
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        });
        Interval preInterval = null;

        for (Interval curInterval : intervals) {
            if (preInterval == null || preInterval.end < curInterval.start) {
                res.add(curInterval);
                preInterval = curInterval;
            }
            else if (preInterval.end < curInterval.end) {
                preInterval.end = curInterval.end;
            }
        }
        return res;
    }
}
```

## 3. Time & Space Complexity

**Scan Line:** 时间复杂度O(nlogn), 空间复杂度O(n)
