构建乘积数组

一、需求

  • 给定一个数组 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]。不能使用除法。

示例:

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

提示:

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

二、暴力法

2.1  思路分析

  1. 这个题目的意思可以这样理解,b[i]的值就是a数组中除了a[i]之外所有值的的乘积,那么我们只要利用循环求出每一个b[i]就好了;
  2. 自定义一个乘积函数product,参数为数组 a 和下标 i,作用是求除了a[i]元素,其余所有元素的乘积;
  3. 该暴力法的时间复杂度是O(n^2),空间复杂度为O(n),存在超时问题,貌似只要数组的长度超过10^5就会超时;

2.2  代码实现

class Solution {
    public int[] constructArr(int[] a) {
        int[] b = new int[a.length];
        for(int i = 0; i < b.length; i++) {
            b[i] = product(a, i);
        }
        return b;
    }
    //该方法用来返回除a[i]之外的所有元素乘积
    public int product(int[] a, int i) {
        int res = 1;
        if(i == 0) {
            for(int j = 1; j < a.length; j++) {
                res *= a[j];
            }
        } else {
            for(int j = 0; j < i; j++) {
                res *= a[j];
            }
            for(int j = i + 1; j < a.length; j++) {
                res *= a[j];
            }
        }
        return res;
    }
}

三、利用表格分区

3.1  思路分析

  1. 具体思路参考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/
  2. 定义left数组来存储表格下三角各行的乘积,定义right数组来存储表格上三角各行的乘积;
  3. 将left数组与right数组对应的值相乘就是要求的b[i];

3.2  代码实现

class Solution {
    public int[] constructArr(int[] a) {
        if(a.length == 0 || a == null) return new int[0];
        int len = a.length;
        int[] left = new int[len];
        int[] right = new int[len];
        left[0] = 1;
        right[len - 1] = 1;
        //保存下三角各行乘积
        for(int i = 1; i < len; i++) {
            left[i] = left[i - 1] * a[i - 1];
        }
        //保存上三角各行乘积
        for(int i = len - 2; i >= 0; i--) {
            right[i] = right[i + 1] * a[i + 1];
        }
        //求结果
        for(int i = 0; i < len; i++) {
            left[i] = left[i] * right[i];
        }
        return left;
    }
}

3.3  复杂度分析

  • 时间复杂度为O(n);
  • 空间复杂度为O(n);

四、表格分区优化

4.1  思路分析

  1. 上述代码中创建了两个数组,在这里可用变量代替一个数组,来对空间复杂度优化;
  2. 比如我们定义变量tmp,利用tmp求上三角各行的乘积,每求一行乘积就更新对应的b[i],相比第一种,效率也提高了;

4.2  代码实现

class Solution {
    public int[] constructArr(int[] a) {
        if(a.length == 0 || a == null) return new int[0];
        int len = a.length;
        int[] b = new int[len];
        b[0] = 1;
        int tmp = 1;
        //保存下三角各行乘积
        for(int i = 1; i < len; i++) {
            b[i] = b[i - 1] * a[i - 1];
        }
        //求结果
        for(int i = len - 2; i >= 0; i--) {
            tmp *= a[i + 1];
            b[i] *= tmp; 
        }
        return b;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值