##238. Product of Array Except Self
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.)
解题思路: 不能用除法,又必须是线性的loop, 所以,想到左右乘法。 i 左边的数字相乘保存起来,右边的数字相乘保存起来。
public int[] productExceptSelf(int[] nums) {
int[] res = new int [nums.length];
int left = 1;
int right = 1;
res[0] = 1; //不要忘了
for (int i = 1; i< nums.length; i++){
left *= nums[i-1];
res[i] = left;
}
for (int i = nums.length-2; i >= 0; i--){
right *= nums[i+1];
//res[i]中的值是上面一个循环计算出的。
res[i] = res[i] *right;
}
return res;
}