Javascript Algorithms

Product of all the elements of the array, except self

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Bài giải :


var productExceptSelf = function(nums) {
    const length = nums.length
    const left = Array(length).fill(nums[0])
    const right = Array(length).fill([nums[length-1]])
    for(var i=1;i<length;i++){
        left.push(left[i-1]*nums[i])
    }
    for(var j=length-2;j>0; j--){
        right[j]=right[j+1]*nums[j]
    }
    return nums.map((v,i)=>(left[i]*right[i]))
};

Bình luận về bài viết này