首页 > 代码库 > 52、构建乘积数组

52、构建乘积数组

题目:给定一个数组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]* 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];

 

注意: 用一个变量B【】表示,C和D

技术分享
import java.util.ArrayList;
public class Solution {
    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 (int i = 1; i < A.length; i++) {
            //计算c[i]
            B[i] = B[i - 1] * A[i - 1];
        }
        double temp = 1;
        for (int i = A.length - 2; i >= 0; i--) {
            //计算D【i】
            temp *= A[i + 1];
            //计算c[i] * d[i]
            B[i] *= temp;
        }
        return B;
        
    }
}
View Code

测试:

1、顺序的

2、有正有负

3、正和0

4、负和0

5、数组就2个元素

52、构建乘积数组