Most concise Java solution


  • 1

    Start from index 1 and compare current interval with its previous one.
    If there is no overlap save the previous one, otherwise save the information in the current one


    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            Collections.sort(intervals, (a,b)->a.start-b.start);
            List<Interval> res = new LinkedList<>();
            int n = intervals.size();
            if(n==0) return res;
            for(int i=1;i<n;++i){
                if(intervals.get(i-1).end<intervals.get(i).start){
                    res.add(intervals.get(i-1));
                }else{
                    intervals.get(i).start=Math.min(intervals.get(i-1).start, intervals.get(i).start);
                    intervals.get(i).end=Math.max(intervals.get(i-1).end, intervals.get(i).end);
                }
            }
            
            res.add(intervals.get(n-1));
            
            return res;
        }
    }

Log in to reply
 

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