zoukankan      html  css  js  c++  java
  • lintcode:合并区间

    题目:

    合并区间

     给出若干闭合区间,合并所有重叠的部分。

    样例

    给出的区间列表 => 合并后的区间列表:

    [                     [
      [1, 3],               [1, 6],
      [2, 6],      =>       [8, 10],
      [8, 10],              [15, 18]
      [15, 18]            ]
    ]
    挑战

    O(n log n) 的时间和 O(1) 的额外空间。

    解题:

    按照start对区间进行排序

    实现Comparator接口,重写compare方法

     

        private class IntervalComparator implements Comparator<Interval>{
            public int compare(Interval a,Interval b){
                return a.start - b.start;
            }
        }

     

    对相邻的两个区间:last,cur.last在前,cur在后

    if last.end >= cur.start 前一个区间的结束包括了后一个区间的开始:

      这两个区间需要合并,更新last.end = Max(last.end,cur.end)

    else

      last 加入的 list中

      更新 list = cur

    /**
     * Definition of Interval:
     * public class Interval {
     *     int start, end;
     *     Interval(int start, int end) {
     *         this.start = start;
     *         this.end = end;
     *     }
     */
    
    class Solution {
        /**
         * @param intervals: Sorted interval list.
         * @return: A new sorted interval list.
         */
        public List<Interval> merge(List<Interval> intervals) {
            // write your code here
            if(intervals == null || intervals.size()<=1){
                return intervals;
            }
            Collections.sort(intervals,new IntervalComparator());
            List<Interval> result = new ArrayList<Interval>();
            Interval last = intervals.get(0);
            for(int i=1;i<intervals.size();i++){
                Interval curt = intervals.get(i);
                if(curt.start<=last.end){
                    last.end = Math.max(last.end,curt.end);
                }else{
                    result.add(last);
                    last = curt;
                }
            }
            result.add(last);
            return result;
        }
        private class IntervalComparator implements Comparator<Interval>{
            public int compare(Interval a,Interval b){
                return a.start - b.start;
            }
        }
    
    }

    参考链接:http://www.jiuzhang.com/solutions/merge-intervals/

  • 相关阅读:
    基于Docker的Mysql主从复制搭建
    Docker操作命令——查看、停止、删除容器
    Git命令
    未定义数组下标: 0
    zookeeper-3.4.14单机多端口集群搭建
    使用MAT分析dump文件定位程序问题
    intellij idea2019.1中文破解版安装
    vscode打造golang开发环境
    python项目开发环境模块安装记录
    shell用法
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4870780.html
Copyright © 2011-2022 走看看