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]
.
分析题目:既然不让用除法,就只能用乘法,用i左边的乘以i右边的就是结果啦。
代码如下:
public int[] productExceptSelf(int[] nums) {
int len=nums.length;
int[] res=new int[len];
res[len-1]=1;
// 得到i右边所有数的乘积
for(int i=len-2;i>=0;i--)
{
res[i]=res[i+1]*nums[i+1];
}
int left=1;
//i右边的乘以i左边的即为结果
for(int i=0;i<=len-1;i++)
{
res[i]*=left;
left*=nums[i];
}
return res;
}