题目:
给定一个整数数组A。
定义B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], 计算B的时候请不要使用除法。
样例
给出A=[1, 2, 3],返回 B为[6, 3, 2]
思路:
分别再定义两个数组C,D,保存的是 A[0] * ... * A[i-1]
A[i+1] * ... * A[n-1] 的值。
然后 B[i] = C[i] * D[i]。
代码:
public List<Long> productExcludeItself(List<Integer> nums) {
// write your code here
List<Long> res = new ArrayList<>();
int len = nums.size();
long[] temp1 = new long[len];
long[] temp2 = new long[len];
temp1[0] = (long)1;
temp2[len-1] = (long)1;
for (int i = 1; i < len; i++) {
temp1[i] = temp1[i-1] * (long)nums.get(i-1);
temp2[len-i-1] = temp2[len-i] * (long)nums.get(len-i);
}
for (int i = 0; i < nums.size(); i++) {
res.add(temp1[i]* temp2[i]);
}
return res;
}