Title Description
Given an array A [0,1, ..., n- 1], please construct an array B [0,1, ..., n- 1], where B is the element B [I] = A [0] A [ . 1] ... A * [. 1-I] A [I +. 1] ... * A [n--. 1]. You can not use the division. (Note: The predetermined B [0] = A [1 ] * A [2] * ... * A [n-1], B [n-1] = A [0] * A [1] * ... * A [n -2];)
Ideas analysis
- An idea: violent solution, two cycles, the complexity of O (N ^ 2).
- Two ideas: B [i] value can be regarded as the value of the matrix is diagonal, corresponding to the calculated upper and lower triangular, then multiplying the two parts.
- For the sake of simplicity, also use two memory arrays up and down triangle, and finally traversed multiplied.
Figure borrow cattle guest book to prove safety
Code
public int[] multiply(int[] A) {
int[] B=new int[A.length];
B[0]=1;
//从上往下计算下三角
for (int i = 1; i <A.length; i++) {
B[i]=B[i-1]*A[i-1];
}
//从下往上计算上三角
int tmp=1;
for (int i = A.length-2; i >=0 ; i--) {
tmp*=A[i+1];
B[i]*=tmp;
}
return B;
}