Java solution


  • 1
    M
       public List<Interval> merge(List<Interval> intervals) {
        ArrayList<Interval> result = new ArrayList<Interval>();
        
        if(intervals.size()<1){
            return result;
        }
        //sort the array
        Collections.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval x, Interval y) {
                return Integer.compare(x.start,y.start);                
            }
            });
        int n=0;
        result.add(intervals.get(0));
        Interval j = result.get(0);
        for(Interval i: intervals) {
            if(j.end<i.start){
               result.add(i);
               n++;
               j = result.get(n);
            }
            else {
                j.start = Math.min(i.start,j.start);
                j.end = Math.max(i.end,j.end);
            }
            
        }
        return result;
        
    }
    

    }


Log in to reply
 

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