Simple Java Solution


  • 0
    D
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            List<Interval> res = new ArrayList<>();
            int size = intervals.size();
            if (size == 0 || intervals == null) return res;
            if (size == 1 ) return intervals;
            intervals.sort((i1, i2) -> Integer.compare(i1.start, i2.start));
            
            // get start and end from the first interval
            int start = intervals.get(0).start;
            int end = intervals.get(0).end;
            
            // loop from the second to the last 
            for (int i = 1; i < size; i++) {
                Interval current = intervals.get(i);
                if (current.start <= end) end = Math.max(current.end, end);
                else {
                    res.add(new Interval(start, end));
                    // set new start and end
                    start = current.start;
                    end = current.end;
                }
            }
            // add the last interval
            res.add(new Interval(start, end));
            return res;
        }
    }

Log in to reply
 

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