Accepted Java solution.

  • 0
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            if(intervals.size()==1) return intervals;
            if(intervals.size()==0) return new ArrayList<Interval>();
            Collections.sort(intervals, new IntervalComparator());
            boolean have_merge;
                have_merge = false;
                for(int i=1;i<intervals.size();i++){
                    if(intervals.get(i).start <= intervals.get(i-1).end){
                        Interval inter = new Interval(intervals.get(i-1).start,Math.max(intervals.get(i).end,intervals.get(i-1).end));
                        intervals.set(i-1, inter);
                        have_merge = true;
                        break; //break after 1 merge
            }while(have_merge);//finish loop if no more merge is found
            return intervals;
        class IntervalComparator implements Comparator<Interval> {
                public int compare(Interval i1, Interval i2) {
                    if(i1.start - i2.start !=0 )
                        return i1.start - i2.start;
                        return i1.end - i2.end;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.