Javascript solution O(n)


  • -1
    C
    /**
     * Definition for an interval.
     * function Interval(start, end) {
     *     this.start = start;
     *     this.end = end;
     * }
     */
    /**
     * @param {Interval[]} intervals
     * @return {Interval[]}
     */
    var merge = function(intervals) {
    	intervals = intervals.sort(function(val1, val2){
    		if(val1.start>val2.start){
    			return 1;
    		}else if(val1.start<val2.start){
    			return -1;
    		}else{
    			return 0;
    		}
    	})
    
    	var first, last;
    
    	for(var i=1; i<intervals.length; ++i){
    
    		if(intervals[i-1].end>=intervals[i].start){
    			first = intervals[i-1].start;
    			last = intervals[i-1].end>=intervals[i].end?intervals[i-1].end:intervals[i].end;
    			intervals.splice(i-1, 2, new Interval(first, last));
    			--i; // delete two, add one, length=length-1
    		}
    
    	}
    
    	return intervals;
    };

Log in to reply
 

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