238. Product of Array Except Self
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:
Input:[1,2,3,4]
Output:[24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
1 public class Solution { 2 public int[] productExceptSelf(int[] nums) { 3 int n = nums.length; 4 int[] res = new int[n]; 5 res[0] = 1; 6 for (int i = 1; i < n; i++) { 7 res[i] = res[i - 1] * nums[i - 1]; 8 } 9 int right = 1; 10 for (int i = n - 1; i >= 0; i--) { 11 res[i] *= right; 12 right *= nums[i]; 13 } 14 return res; 15 } 16 17 public int[] productExceptSelf(int[] nums) { 18 // Left is an array containing the left products 19 // i.e: left[i] = nums[0] * .... * nums[i-1] 20 int[] left = new int[nums.length]; 21 22 // Right is an array containing the array products 23 //i.e: right[i] = nums[i+1] * nums[i+2] * .... * nums[len(nums) - 1] 24 int[] right = new int[nums.length]; 25 26 left[0] = 1; 27 for (int i = 1; i < nums.length; i++) { 28 left[i] = left[i-1] * nums[i-1]; 29 } 30 31 right[nums.length - 1] = 1; 32 for (int i = nums.length - 2; i >= 0; i--) { 33 right[i] = right[i+1] * nums[i+1]; 34 } 35 36 int[] product = new int[nums.length]; 37 for (int i = 0; i < product.length; i++) { 38 product[i] = left[i] * right[i]; 39 } 40 41 return product; 42 } 43 }