74.构建乘积数组

给定一个数组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]。

不能使用除法。

数据范围:

输入数组长度 [0,20]。

样例:

输入:[1, 2, 3, 4, 5]
输出:[120, 60, 40, 30, 24]

思考题:

  • 能不能只使用常数空间?(除了输出的数组之外)

代码:

class Solution {
    public int[] multiply(int[] A) {
        //处理边界情况:输入数组为空或长度为0
        if(A == null||A.length == 0)return new int[0];
        //n为A数组长度
        int n = A.length;
        //B为结果数组
        int[] B = new int[n];
        //第一个元素左边没有元素,乘积为1
        B[0] = 1;
        //第一轮遍历:计算每个元素左边的乘积并存入B
        //p用于累积左乘积
        for(int i = 1,p = A[0];i<n;i++){
            B[i] = p;
            p*=A[i];
        }
        //第二轮遍历:计算每个元素右边的乘积并与B中的左乘积相乘
        //p用于累积右乘积
        for(int i = n-2,p = A[n-1];i>=0;i--){
            B[i]*=p;
            p*=A[i];
        }
        //返回结果数组
        return B;
    }
}
posted @ 2025-06-02 13:03  回忆、少年  阅读(6)  评论(0)    收藏  举报