Simple java solution with O(1) space complexity


  • 0
    M

    public List<Interval> merge(List<Interval> intervals) {
    if(intervals ==null || intervals.size()<2)
    return intervals;

        // comparator for list
       
            Collections.sort(intervals, new Comparator<Interval>(){
                
               @Override
                public int compare(Interval in1, Interval in2){
                    return Integer.compare((int)in1.start , (int)in2.start);
                  
                }
                
            });
       
        for(int i = 1; i < intervals.size(); i++){
            if((intervals.get(i).end <= intervals.get(i-1).end)){
                intervals.remove(i);i--;continue;
            }
                
            if ((intervals.get(i).start <= intervals.get(i-1).end) && (intervals.get(i).end >= intervals.get(i-1).end)){
                intervals.get(i-1).end = intervals.get(i).end;
                intervals.remove(i);
                i--;
            }   
        }
        return intervals;
    }
    

    }


Log in to reply
 

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