# C#LeetCode刷题之#56-合并区间（Merge Intervals）

Given a collection of intervals, merge all overlapping intervals.

Input: [[1,3],[2,6],[8,10],[15,18]]

Output: [[1,6],[8,10],[15,18]]

Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Input: [[1,4],[4,5]]

Output: [[1,5]]

Explanation: Intervals [1,4] and [4,5] are considerred overlapping.

```public class Program {

public static void Main(string[] args) {
var intervals = new List<Interval> {
{ new Interval(1, 3) },
{ new Interval(2, 6) },
{ new Interval(8, 10) },
{ new Interval(15, 18) }
};

var res = Merge(intervals);
ShowArray(res);

}

private static void ShowArray(IList<Interval> list) {
foreach(var num in list) {
Console.Write(\$"({num.start},{num.end}) ");
}
Console.WriteLine();
}

public static IList<Interval> Merge(IList<Interval> intervals) {
var res = new List<Interval>();
if(intervals.Count == 0) return res;
intervals = intervals.OrderBy(i => i.start).ToList();
for(var i = 1; i < intervals.Count; i++) {
if(intervals[i].start <= res[res.Count - 1].end) {
res[res.Count - 1].end =
Math.Max(intervals[i].end, res[res.Count - 1].end);
} else {
}
}
return res;
}

public class Interval {
public int start;
public int end;
public Interval() { start = 0; end = 0; }
public Interval(int s, int e) { start = s; end = e; }
}

}```

`(1,6) (8,10) (15,18)`

(3)