Simple and easy to understand Java solution


  • 0
    M
    /**
     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
     */
    class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            if (intervals == null || intervals.isEmpty()) {
                return intervals;
            }
            // Sort intervals by interval.start
            intervals.sort(Comparator.comparingInt(i -> i.start));
            List<Interval> mergeIntervals = new LinkedList<>();
    
            Interval newInterval = new Interval(intervals.get(0).start, intervals.get(0).end);
            for (Interval interval : intervals) {
                if (interval.start > newInterval.end) {
                    // There is no overlap between newInterval and interval
                    mergeIntervals.add(newInterval);
                    newInterval = new Interval(interval.start, interval.end);
                } else if (newInterval.end < interval.end) {
                    newInterval.end = interval.end;
                }
            }
            mergeIntervals.add(newInterval);
    
            return mergeIntervals;
        }
    }
    

Log in to reply
 

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