O(n) time, O(1) space, Simple!


  • 0
    G
    /**
     * @param {number[]} nums
     * @return {number[]}
     */
    var productExceptSelf = function(nums) {
        // nums = [1, 2, 3, 4]
        var r = [0];
        var all = 1;
        // r = [0, (all = 1)*1, (all = 1)*2, (all = 1*2)*3]
        for (var i = 1; i < nums.length; i++) {
            all *= nums[i - 1];
            r.push(all);
        }
        all = 1;
        // r = [0, 1*(all = 3*4), 1*2*(all = 4), 1*2*3]
        for (i = nums.length - 1; i > 0; i--) {
            all *= nums[i];
            r[i - 1] *= all; 
        }
        // r = [all=(2*3*4), 1*3*4, 1*2*4, 1*2*3]
        r[0] = all;
    
        return r;
    };
    

Log in to reply
 

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