题目:
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…A[i-1]*A[i+1]…*A[n-1]。不能使用除法。
思路:
因为要求不能用除法,所以可以把B[i] 看做是 C[i] = A[0]*A[1]*…*A[i-1] 和D[i] = A[i+1]*…*A[n-1]的乘积。所以可以将C[i]和D[i]先求出,然后再求得B[i]。
代码:
public class Solution {
public int[] multiply(int[] A) {
int length = A.length;
int[] B = new int [length];
if(A == null) return B;
int [] array1 = new int[length];//C[i]
int [] array2 = new int[length];//D[i]
array1[0] = 1;
array2[0] = 1;
for(int i = 1;i < length;++i){
array1[i] = A[i -1] * array1[i - 1];
array2[i] = A[length - i] * array2[i - 1];
}
for(int i = 0; i < length; ++i){
B[i] = array1[i] * array2[length - i - 1];
}
return B;
}
}