题目:
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]
.
解析:
题目是说给定一个数组nums,返回一个输出数组output,里面每个元素outpus[i]是nums中除了第i个元素的乘积。
最容易想到的是先求nums数组所有数的乘积cj, 然后output[i] = cj / nums[i]。不过题目规定不能用除法所以不可取。
正解是:由于output[i] = nums[0...i-1] * nums[i+1,...n-1],所以可以先求出nums[0,...,i-1],然后与[i+1,...,n-1]相乘
比如[1,2,3,4] , 新建数组返回数组output=[1,1,1,1],output[i] = nums[0] * nums[1] *...*nums[i-1],1<=i<3
所以左边相乘的结果为output = [1,1,2,6],而后与右边的相乘。
output[i] = output[i] * nums[i+1]*...*nums[3], 0<=i<3;
i = 2时,output[2] = output[2] * nums[3] = 2*4 = 8
i = 1时,output[1] = output[1] * nums[2]*nums[3] = 1*3*4=12
i = 0时,output[0] = output[0] * nums[1] * nums[2] * nums[3] = 24
即output = [24,12,8,6]
代码如下:
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] output = new int[nums.length];
//为output赋初值
for (int i=0;i<nums.length;i++){
output[i] = 1;
}
int left = 1;
//output先保存左边的乘积
for (int i=1;i<nums.length;i++){
//第一个数的左边没有,所以i初值为1
left *= nums[i-1];
output[i] = left;
}
int right = 1;
//然后再与右边的乘积相乘
for (int i=nums.length-2;i>=0;i--){
//最后一个数的右边没有,所以i初值为n-2
right *= nums[i+1];
output[i] *= right;
}
return output;
}
}