My java solution


  • 0
    L
    public List<Interval> merge(List<Interval> intervals) {
        if(intervals==null||intervals.size()==0) return new ArrayList<Interval>();
        List<Interval> result=new ArrayList<Interval>();
        intervals.sort(new Comparator<Interval>(){//sort intervals by start ascending order
            @Override
            public int compare(Interval o1,Interval o2){
                return o1.start-o2.start;
            }
        });
        Interval temp=intervals.get(0);
        for(int i=1;i<intervals.size();i++){
            if(intervals.get(i).start>temp.end){
                result.add(temp);
                temp=intervals.get(i);
            }
            else if(intervals.get(i).end>temp.end){
                temp.end=intervals.get(i).end;
            }
        }
        if(temp!=null) result.add(temp);
        return result;
    }

Log in to reply
 

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