构建乘积数组
构建乘积数组
http://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46
给定一个数组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[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)
public class Solution {
public int[] multiply(int[] A) {
if (A == null || A.length < 2){
return new int[0];
}
//审题可知,B[i]即为 除数组A中A[i] 外,其它数的乘积
//分别从前-->后、再从后-->前分两次遍历求值即可
int[] B = new int[A.length];
int base = 1;
for (int i = 0; i < A.length; i++) {
B[i] = base;
base *= A[i];
}
base = 1;
for (int i = A.length - 1; i > -1; i--) {
B[i] *= base;
base *= A[i];
}
return B;
}
}