力扣---剑指 Offer 66. 构建乘积数组

发布时间 2023-04-12 22:07:49作者: Owlwu

给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。

 

示例:

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

提示:

所有元素乘积之和不会溢出 32 位整数
a.length <= 100000

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/gou-jian-cheng-ji-shu-zu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


 

某个位置的值,等于其左边所有数的乘积,再乘以右边所有数的乘积。

时间复杂度 O(n),空间复杂度 O(1)。(返回的结果占用的空间不算到空间复杂度中)

class Solution {
    public int[] constructArr(int[] a) {
        if (a.length < 2) {
            return a;
        }
        // 从左到右保存之前值的乘积。
        int[] product = new int[a.length];
        product[0] = a[0];
        for (int i = 1; i < a.length - 1; i ++) {
            product[i] = product[i - 1] * a[i];
        }
        // 保存从右到左的乘积。
        int tem = 1;
        for (int i = a.length - 1; i > 0; i --) {
            // 当前位置的值,等于左边所有数的乘积乘以右边所有数的乘积。
            product[i] = product[i - 1] * tem;
            tem *= a[i];
        }
        product[0] = tem;
        return product;
    }
}