JZ51-构建乘积数组

构建乘积数组

https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

class Solution {
    public int[] multiply(int[] A) {
        if (A == null || A.length <= 1) {
            return null;
        }
        int n = A.length;
        int[] B = new int[n];
        for (int i = 0, product = 1; i < n; product *= A[i], i++) {       /* 从左往右累乘 left[i]用B[i]代替 */
            B[i] = product;
        }
        for (int i = n - 1, product = 1; i >= 0; product *= A[i], i--) { /* 从右往左累乘 */
            B[i] *= product; //要在左边的基础上
        }
        return B;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务