Time Limit Exceeded for a JavaScript Solution O(n) space and O(n) time


  • 0
    S
    /**
     * @param {string} s
     * @return {number}
     */
    var calculate = function(s) {
        
        var signs = [],
            nums = [],
            num,
            i;
        
        nums = s.replace(/\s/g, '').split(/\+|\-|\*|\/|\ /).map(function(e) { return parseInt(e) }); 
        signs = s.replace(/\s/g, '').split(/[0-9]+/);
        signs.splice(0, 1);
        signs.splice(signs.length - 1, 1);
        
        for(i = 0; i < signs.length;){
            if(signs[i] === '*'){
                num = nums[i] * nums[i + 1];
                nums.splice(i, 2, num);
                signs.splice(i, 1);
            } else if(signs[i] === '/'){
                num = Math.floor(nums[i] / nums[i + 1]);
                nums.splice(i, 2, num);
                signs.splice(i, 1);
            } else {
                i++;
            }
        }
        
        num = nums.shift();
        for(i = 0; i < signs.length; i++) {
            if(signs[i] === '+'){
                num += nums.shift();
            } else if (signs[i] === '-'){
                num -= nums.shift();
            }
        }
        
        return num;
    };
    

Log in to reply
 

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