Javascript solution 92ms


  • 0
    M

    var summaryRanges = function(nums) {

    //method 1: 92ms one pass
    /*
    var start = 0;
    var ans = [];
    //modify original array
    nums.push("#");
    for (var i = 1; i < nums.length; i++) {
        if ((nums[i] - nums[start]) !== (i - start)) {
            if (start !== (i-1)) {
                ans.push(nums[start] + "->" + nums[i-1]);
            } else {
                ans.push(nums[start].toString());
            }
            start = i;
        }
    }
    return ans;
    */
    
    
    //method 2: 92ms  two pointers
    var ans = [];
    for (var i = 0; i < nums.length; i++) {
        var str = nums[i];
        var start = i;
        while (i+1 < nums.length && nums[i+1] - nums[i] === 1) {
            i++;
        }
        if (i > start) {
            str = nums[start] + "->" + nums[i];
        }
        ans.push(str.toString());
    }
    return ans;
    

    };


Log in to reply
 

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