Accepted Java solution.


  • 0
    C
    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;
            do{
                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);
                        intervals.remove(i);
                        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> {
                @Override
                public int compare(Interval i1, Interval i2) {
                    if(i1.start - i2.start !=0 )
                        return i1.start - i2.start;
                    else
                        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.