Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
不使用除法和额外空间的情况下
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Solution
[1,a1,a1a2,.....,a1a2..an-1]
[a2a3...an,an*an-1,an,1]相乘即可
divide the multiplying process into two passes.
class Solution {
public int[] productExceptSelf(int[] nums) {
int left=1;
int right=1;
int[] res=new int[nums.length];
for(int i=0;i<nums.length;i++){
res[i]=left;
left*=nums[i];
}
for(int i=nums.length-1;i>=0;i--){
res[i]*=right;
right*=nums[i];
}
return res;
}
}
网友评论