Easy to understand java solution


  • 0
    Q
    public List<Interval> merge(List<Interval> intervals) {
        int n = intervals.size();
        List<Interval> rt = new ArrayList();
        if(n == 0) return rt;
        
        Collections.sort(intervals, new ItvComparator());
        for(int i = 0; i < n-1; i++){
            Interval cur = intervals.get(i);
            Interval next = intervals.get(i+1);
            if(cur.end >= next.start){
                intervals.set(i, null);
                intervals.set(i+1, new Interval(cur.start, cur.end > next.end? cur.end: next.end));
            }
        }
        
        for(Interval i : intervals){
            if(i != null){
                rt.add(i);
            }
        }
        return rt;
    }
    
    class ItvComparator implements Comparator<Interval>{
        public int compare(Interval a, Interval b){
            return a.start - b.start;
        }
    }
    

Log in to reply
 

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