public class Solution
{
public IList<Interval> Merge(IList<Interval> intervals)
{
var len = intervals.Count;
if (len == )
{
return intervals;
}
var list = intervals.OrderBy(x => x.start).ToList();
int i = ;
while (i < list.Count)
{
int j = i;
while (i < list.Count - && list[j].end >= list[i + ].start)
{
//可以融合
//前项修改,后项删除
list[j].start = Math.Min(list[j].start, list[i + ].start);
list[j].end = Math.Max(list[j].end, list[i + ].end);
list.RemoveAt(i + );
}
i++;
}
return list;
}
}
提供一个python版本的实现:
class Solution:
def merge(self, intervals: 'List[Interval]') -> 'List[Interval]':
intervals = sorted(intervals,key=lambda x:[x[],-x[]])
i =
while i < len(intervals) - :
curbegin = intervals[i][]
curend = intervals[i][] nextbegin = intervals[i+][]
nextend = intervals[i+][]
if curend >= nextbegin:
intervals.pop(i)
intervals[i]=[min(curbegin,nextbegin),max(curend,nextend)]
else:
i +=
return intervals