A Javascript Solution


  • 0
    P
    /**
     * @param {Interval[]} intervals
     * @return {Interval[]}
     */
    var merge = function(intervals) {
       if(intervals === undefined) {
            return intervals;
        }
    
        intervals.sort(function(a, b) {
            return a.start - b.start;
        });
    
        var mergedIntervals = [];
        var i = 0, j;
        while(i < intervals.length) {
            var segment = new Interval(intervals[i].start, intervals[i].end);
            j = i + 1;
            while(j < intervals.length && intervals[j].start <= segment.end) {
                segment.end = Math.max(segment.end, intervals[j].end);
                j++;
            }
            mergedIntervals.push(segment);
            i = j;
        }
    
        return mergedIntervals;
    };
    

Log in to reply
 

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