Given an array of n integers where n > 1, nums
and return an array output
such that's equal to output[i]
th E 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 solve it with constant space complexity? (note:the output array does not count as extra space for the purpose of space complexity analysis.)
Subscribe to see which companies asked this question
1 Public classSolution {2 Public int[] Productexceptself (int[] nums) {3 int[] ans =New int[nums.length];4 for(inti = 0,tmp = 1;i < nums.length; i++){5Ans[i] =tmp;6TMP *=Nums[i];7 }8 for(inti = nums.length-1,tmp = 1;i >= 0; i--){9Ans[i] *=tmp;TenTMP *=Nums[i]; One } A returnans; - } -}
Iterate from left to right, and then from right to left, you get the answer.
238. Product of Array Except self Java Solutions