[leedcode 57] Merge Intervals

來源:互聯網
上載者:User

標籤:

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;        }    }}

 

[leedcode 57] Merge Intervals

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.