Question:

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

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

Solution:

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[]}
  4. */
  5. var productExceptSelf = function(nums) {
  6. const len = nums.length;
  7. const result = new Array(len);
  8. result.fill(1);
  9. // 计算左边
  10. for (let i = 1; i < len; i++) {
  11. result[i] = result[i-1] * nums[i-1];
  12. }
  13. // 右边
  14. for (let j = len - 2; j >= 0; j--) {
  15. result[j] *= nums[j+1];
  16. nums[j] *= nums[j+1];
  17. }
  18. return result;
  19. };

Runtime: 88 ms, faster than 78.80% of JavaScript online submissions for Product of Array Except Self.