• [leedcode 57] Merge Intervals


    Given a collection of intervals, merge all overlapping intervals.

    For example,
    Given [1,3],[2,6],[8,10],[15,18],
    return [1,6],[8,10],[15,18].

    /**
     * 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) {
            //采用的是和Insert Interval一样的思想,只不过最开头要先排序一下,用到了java的Collections.sort(List<Interval> list, Comparator<? super Interval> c)
            //需要自己实现了一个Comparator的compare方法
            //注意compare的实现方式!!
            //因为已经排过序,并且是从头开始遍历,因此不会出现后面遍历的在temp之前的情况,所以注释部分可有可无
            List<Interval> res=new ArrayList<Interval>();
            if(intervals.size()<1) return res;
            Collections.sort(intervals,new IntervalCom());///
            Interval temp=intervals.get(0);
            for(int i=1;i<intervals.size();i++){
                Interval cur=intervals.get(i);
               /* if(cur.end<temp.start){
                    //res.add(cur);
                }else{*/
                    if(cur.start>temp.end){
                        res.add(temp);
                        temp=cur;
                    }else{
                        int start=Math.min(temp.start,cur.start);
                        int end=Math.max(temp.end,cur.end);
                        temp=new Interval(start,end);
                    }
                //}
                
            }
            res.add(temp);
            return res;
            
        }
        public class IntervalCom implements Comparator<Interval>{////
            public int compare(Interval o1,Interval o2){
                return o1.start-o2.start;
            }
        }
    }
  • 相关阅读:
    Python字典处理技巧
    javascript常用对象
    8. 异步操作
    九度OnlineJudge之1022:游船出租
    直方图(下)
    MySQL中关于日期、时间的数据类型和函数
    libvirt(virsh命令介绍)
    11g的alert日志路径
    使用GridView来获取xml文件数据
    MediaPlayer视频播放器
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4641830.html
Copyright © 2020-2023  润新知