Javascript beats 100%


  • 2
    /**
     * Definition for an interval.
     * function Interval(start, end) {
     *     this.start = start;
     *     this.end = end;
     * }
     */
    /**
     * @param {Interval[]} intervals
     * @return {number}
     */
    var minMeetingRooms = function(intervals) {
    	var starts = intervals.concat().sort(function(a, b) {
    		return a.start - b.start;
    	});
    	var ends = intervals.sort(function(a, b) {
    		return a.end - b.end;
    	});
    	var rooms = 0;
    	var end = 0;
    	for (var i = 0; i < intervals.length; i++) {
    		if (starts[i].start < ends[end].end) {
    			rooms++;
    		} else {
    			end++;
    		}
    	}
    	return rooms;
    };

  • 0
    T

    Can I know why do you use concat() for var starts, and what does it do? Thanks.


  • 2
    R

    @twjeen

    The sort method returns the original array, so if you didn't do .concat(), the latter ends assignment statement would have mutated the original array. Hence @billie523 used intervals.concat() to shallow copy an array.

    intervals.slice() would work just fine too.


  • 0

    @raejin said in Javascript beats 100%:

    @twjeen

    The sort method returns the original array, so if you didn't do .concat(), the latter ends assignment statement would have mutated the original array. Hence @billie523 used intervals.concat() to shallow copy an array.

    intervals.slice() would work just fine too.

    Exactly! Thank you twjeen!


Log in to reply
 

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