0604-2020-LEETCODE-238-除自身以外数组的乘积.经典.66-构建乘积数组(前缀后缀乘积)

题目要求不能用除法,所以还是从乘积入手。
自己写的前缀积 * 后缀积代码,是比较正常的传统解题思路,比较容易想到。
受网友启发

	public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] resL = new int[len];
        resL[0] = nums[0];
        int[] resR = new int[len];
        resR[len - 1] = nums[len - 1];
        for(int i = 1;i < len;i++){
            resL[i] = resL[i - 1] * nums[i];
        }
        for(int i = len - 2;i >= 0;i--){
            resR[i] = resR[i + 1] * nums[i];
        }
        int[] res = new int[len];
        for(int i = 0;i < len;i++){
            if(i == 0) res[i] = resR[1];
            else if(i == len - 1) res[i] = resL[len - 2];
            else res[i] = resL[i - 1] * resR[i + 1];
        }
        return res;
    }

将空间复杂度缩小为O(1),不计算输出数组的空间复杂度
代码来源:评论区
https://leetcode-cn.com/problems/product-of-array-except-self/comments/

	public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int left = 1;
        int right = 1;
        int[] res = new int[len];
        for(int i = 0;i < len;i++){
            res[i] = left;
            left *= nums[i];
        }
        for(int i = len - 1;i >= 0;i--){
            res[i] *= right;
            right *= nums[i];
        }
        return res;
    }

上下三角表格分区思路:
代码来源:
链接:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

class Solution {
    public int[] constructArr(int[] a) {
        if(a.length == 0) return new int[0];
        int[] b = new int[a.length];
        b[0] = 1;
        int tmp = 1;
        for(int i = 1; i < a.length; i++) {
            b[i] = b[i - 1] * a[i - 1];
        }
        for(int i = a.length - 2; i >= 0; i--) {
            tmp *= a[i + 1];
            b[i] *= tmp;
        }
        return b;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值