56. Merge Intervals

Algorithm

  • sort intervals according to start time in increasing order
  • traverse sorted intervals from first interval
    • if current interval is not the first interval and it overlaps the last interval in output list of intervals, merge these two intervals
      • update end time of last interval in output list of intervals to maximum of end times of the two intervals.
    • else add current interval into output list of intervals

Complexity

  • time complexity: O(NlgN)
    • time complexity of sorting: O(NlgN)
  • space complexity: O(N)
    • space used for output list of intervals

Code

/**
 * 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; }
 * }
 */
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        if (intervals == null || intervals.size() == 0) {
            return intervals;
        }
        Collections.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }            
        });
        int size = intervals.size();
        List<Interval> result = new ArrayList();
        result.add(intervals.get(0));
        for (int i = 1; i < size; i++) {
            Interval first = result.get(result.size() - 1);
            Interval second = intervals.get(i);
             if (second.start > first.end) {
                result.add(second);
            } else {
                int newEnd = Math.max(first.end, second.end);
                first.end = newEnd;
            }
        }
        return result;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • “我依然希望故事结束时,能感受到某种坚强的新开始。”--奥黛丽·赫本 一部《修女传》,把彷徨、茫然的奥黛丽带了出来...
    Mina茄子阅读 523评论 0 3
  • 袁庄。­ 一处凉亭,连接着三条水上长廊,水中金鲤自在来去,绿荷袅袅,随风轻舞。一瓣莲花掉落水中,群鱼惊走,荡开一圈...
    道梦鱼阅读 310评论 2 2
  • 我原想着,一定要早睡,不可再熬夜了,从现在起做个好孩子,却忘了,早睡可以早醒,呵呵,我已不是孩子,这老年人的睡眠作...
    豆子之不爱那么多阅读 330评论 0 0