剑指offer66题——构建乘积数组

题目链接:https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&&tqId=11204&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述:给定一个数组 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]。要求不能使用除法。

思路:(说的无法比这个题解更清晰明白了,一句话就是分成i的左右两部分,两部分做乘积就是答案)

https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/java-pythonchao-xiang-xi-jie-ti-by-yang_hang/

public int[] multiply(int[] A) {
        int n = A.length;
        int[] res = new int[n];
        //分成两个部分

        //i左边 部分A[1]...A[i-1]
        for (int i = 0, P = 1; i < n; P *= A[i],i++) {
            res[i] = P;     //res[0] = 1, res[1] = A[0], res[2] = A[0] * A[1],res[3] = A[0]*A[1]*A[2]
        }

        //i右边 部分A[i+1]....A[n-1]
        for (int i = n-1, P = 1;i>=0; P *= A[i],i--){
            res[i] *= P;    //左部分*右部分
        }
        return res;
    }

 

posted @ 2020-07-12 16:31  硬盘红了  阅读(113)  评论(0编辑  收藏  举报