Live2D

构造乘法数组(Java)

/*
*   题目描述
    给定一个数组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];)
    对于A长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。
    示例1
    输入
    [1,2,3,4,5]
    返回值
    [120,60,40,30,24]
    思路:https://blog.nowcoder.net/n/9485f8d4c49e42858e93131809c7ff6a?f=comment
* */
public class MultuplyArray {
    public static void main(String[] args) {
        int [] array = {1,2,3,4,5};
        int [] a = multiply(array);
        for (int i : a) {
            System.out.println(i);
        }
    }

    public static int[] multiply(int[] A) {
        int length = A.length;
        int [] B = new int[length];
        int temp = 1;
        if(A.length==0){
            return B;
        }
        B[0] = 1;
        for(int i =0;i<=length-2;i++){
            temp *= A[i];
            B[i+1] = temp;
        }
        temp = 1;
        int j = length-2;
        for(int i =length-1;i>0;i--,j--){
            temp *= A[i];
            B[j] = B[j]*temp;
        }
        return B;
    }
}
posted @ 2021-01-18 22:29  细雪之舞0213  阅读(104)  评论(0)    收藏  举报