Topic description
Given an array A[0,1,...,n-1], please construct an array B[0,1,...,n-1], where element B[i]=A[ 0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]. Division cannot be used.
topic analysis
There are two solutions to this problem, the second is an optimization based on the first one.
The first solution: B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]=C [i-1]*D[i-1], that is, we require C[i] and D[i], which is equivalent to sacrificing space complexity for time complexity.
The second solution: In the first solution, we found that an additional array is required, which is obviously unnecessary, because the calculation of the B array comes from A, and no redundant C and D arrays are needed, so what is better? way?
We can directly use the B array and implement it with the help of the intermediate variable tmp, see the code for details.
code
The first solution:
function multiply(array) { let C = [], D = [], n = array.length; C[0] = array[0]; for (let i = 1; i < n; i++) { C[i] = array[i] * C[i - 1]; } D[n-1] = array[n-1]; for (let i = n - 2; i >= 0; i--) { D[i] = array[i] * D[i + 1]; } let B = []; B[0]=D[1]; B[n-1]=C[n-2]; for (let i = 1; i < n - 1; i++) { B[i] = C[i-1] * D[i+1]; } return B; }
The second method:
function multiply(array) { let B = [], len = array.length; B[ 0]=1 ; // Calculate the product of the first i - 1 elements for (let i = 1; i < len; i++ ) { B[i] = array[i-1] * B[i - 1]; } let tmp =1 ; // calculate the product of the last N - i elements and concatenate for (let i = len-2; i >=0; i-- ) { tmp*=array[i+1]; B[i]*=tmp; } return B; }