Title: Given an array a[0,1,..., n-1], build an array b[0,1,..., n-1], where the elements in B b[i]=a[0]*a[1]*...*a[i-1]*a[i+1]*...*a[n-1]. You cannot use division.
Ideas:
B[i] = c[i]* D[i]
C[i] = a[0]*a[1]*...*a[i-1] = c[i-1] * A[i-1];
D[i] = a[i-1]*a[i+1]*...*a[n-1] = a[i+1]*d[i+1];
Note: Use a variable B "" to indicate that C and D
Importjava.util.ArrayList; Public classSolution { Public int[] Multiply (int[] A) {//B[i] = c[i]* D[i]//C[i] = a[0]*a[1]*...*a[i-1] = c[i-1] * A[i-1]; //D[i] = a[i-1]*a[i+1]*...*a[n-1] = a[i+1]*d[i+1]; int[] B =New int[A.length]; b[0] = 1; for(inti = 1; i < a.length; i++) { //calculation C[i]B[i] = b[i-1] * a[i-1]; } Doubletemp = 1; for(inti = a.length-2; I >= 0; i--) { //Calculate D "I"Temp *= a[i + 1]; //calculation c[i] * D[i]B[i] *=temp; } returnB; }}
View Code
Test:
1, the Order of
2, there is a positive negative
3, Positive and 0
4, negative and 0
5, array of 2 elements
52. Build the Product array