Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: 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 { 4 int[] array1 = new int[nums.length]; 5 int[] array2 = new int[nums.length]; 6 int[] result = new int[nums.length]; 7 8 array1[0]=1; 9 array2[nums.length-1]=1; 10 for(int i = 1; i<nums.length;i++) 11 { 12 array1[i]=array1[i-1]*nums[i-1]; 13 14 } 15 for(int i=nums.length-2;i>=0;i--) 16 { 17 array2[i]=array2[i+1]*nums[i+1]; 18 } 19 for(int i=0;i<nums.length;i++) 20 { 21 result[i]=array1[i]*array2[i]; 22 } 23 24 return result; 25 26 27 } 28 }