剑指 Offer 66. 构建乘积数组

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

剑指 Offer 66. 构建乘积数组


题目描述

给定一个数组 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.com/problems/gou-jian-cheng-ji-shu-zu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


解题过程

解题思路

规律:
按照上三角和下三角的求法,参考题解: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/
在这里插入图片描述

class Solution {
    public int[] constructArr(int[] a) {
        if(a.length == 0){
            return new int[0];
        }
        int temp = 1;
        int[] b = new int[a.length];
        b[0] = 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--){
            temp = temp * a[i + 1];//上三角
            b[i] = b[i] * temp;//下三角*上三角
        }

        return b;

    }

   
}

补充解法:找规律
在这里插入图片描述

class Solution {
    public int[] constructArr(int[] a) {
        if(a.length == 0){
            return new int[0];
        }
        int multi = 1;
        int [] pre = new int[a.length];
        pre[0] = a[0];
        int [] post = new int[a.length];
        post[0] = a[a.length - 1]; 
        for(int i = 1; i < a.length; i++){
            pre[i] = pre[i - 1] * a[i];
            post[i] = post[i - 1] * a[a.length - 1 - i];
        }

        int [] b = new int[a.length];
        b[0] = post[post.length - 1 - 1];
        for(int i = 1; i < b.length - 1; i++){
            b[i] = pre[i - 1] * post[b.length - 2 - i];
        }
        b[b.length - 1] = pre[a.length - 1 - 1];

        return b;

    }
}

总结

暂时没有总结,待续。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值