首页 > 技术文章 > leetcode56

asenyang 2018-10-06 12:48 原文

public class Solution
    {
        public IList<Interval> Merge(IList<Interval> intervals)
        {
            var len = intervals.Count;
            if (len == 1)
            {
                return intervals;
            }
            var list = intervals.OrderBy(x => x.start).ToList();
            int i = 0;
            while (i < list.Count)
            {
                int j = i;
                while (i < list.Count - 1 && list[j].end >= list[i + 1].start)
                {
                    //可以融合
                    //前项修改,后项删除
                    list[j].start = Math.Min(list[j].start, list[i + 1].start);
                    list[j].end = Math.Max(list[j].end, list[i + 1].end);
                    list.RemoveAt(i + 1);
                }
                i++;
            }
            return list;
        }
    }

 

提供一个python版本的实现:

 1 class Solution:
 2     def merge(self, intervals: 'List[Interval]') -> 'List[Interval]':
 3         intervals = sorted(intervals,key=lambda x:[x[0],-x[1]])
 4         i = 0
 5         while i < len(intervals) - 1:
 6             curbegin = intervals[i][0]
 7             curend = intervals[i][1]
 8 
 9             nextbegin = intervals[i+1][0]
10             nextend = intervals[i+1][1]
11             if curend >= nextbegin:
12                 intervals.pop(i)
13                 intervals[i]=[min(curbegin,nextbegin),max(curend,nextend)]
14             else:
15                 i += 1
16         return intervals

 

推荐阅读