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/

  • 相关阅读:
    线性回归 r python 比较
    vps
    插桩 inline hook 动态二进制插桩的原理和基本实现过程
    duration of lease 1 0.5 0.875 DHCP 租借时间 续租时间 重新绑定时间
    单页应用 cookies处理
    websocket 无需通过轮询服务器的方式以获得响应 同步在线用户数 上线下线 抓包 3-way-handshake web-linux-shell 开发
    code_action
    mysql 表级锁
    mysql 表级锁
    块级标签和行级标签
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4870780.html
Copyright © 2011-2022 走看看