【剑指Offer】面试题66:构建乘积数组

import java.util.Arrays;

/**
 * 面试题66:构建乘积数组
 * 给定一个数组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]。
 * 不能使用除法。
 * (注意:规定
 * B[0] = A[1] * A[2] * ... * A[n-1],
 * B[n-1] = A[0] * A[1] * ... * A[n-2];)
 * 对于A长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。
 *
 * 输入:[1,2,3,4,5]
 * 输出:[120,60,40,30,24]
 *
 * B[0]=A[1]*A[2]*A[3]*A[4]
 * B[1]=A[0]*A[2]*A[3]*A[4]
 * B[2]=A[0]*A[1]*A[3]*A[4]
 * B[3]=A[0]*A[1]*A[2]*A[4]
 * B[4]=A[0]*A[1]*A[2]*A[3]
 *
 * @author dengjie
 * @create 2021-04-17 21:12
 */
public class Solution66 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        int[] multiply = multiplyTwo(arr);
        System.out.println(Arrays.toString(multiply));
    }

    /**
     * 方法一:两个for循环相乘
     * @param A
     * @return
     */
    public static int[] multiply(int[] A) {
        if (A == null || A.length == 0 || A.length == 1){
            return null;
        }
        int[] res = new int[A.length];
        Arrays.fill(res, 1);
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A.length; j++) {
                if (j!=i){
                    res[i] *= A[j];
                }
            }
        }
        return res;
    }

    /**
     * 方法二:时间复杂度为O(n)的解法
     * 思路:可以把B[i]=A[0]A[1]....A[i-1]A[i+1]....A[n-1]。
     * 看成A[0]A[1].....A[i-1]和A[i+1].....A[n-2]A[n-1]两部分的乘积。
     * left[i] = left[i-1]*A[i-1];//C[i]
     * right[i] = right[i+1]*A[i+1]//D[i]
     * res[i] = C[i]*D[i]
     * @param A
     * @return
     */
    public static int[] multiplyTwo(int[] A) {
        if (A == null || A.length == 0 || A.length == 1){
            return null;
        }
        int[] res = new int[A.length];
        //初始化res[0]
        res[0] =1;
        //计算下三角乘积C[i],拿到左边部分的乘积
        for (int i = 1; i < A.length; i++) {
            res[i] = res[i-1] * A[i-1];
        }
        //初始化
        int temp = 1;
        //计算上三角乘积D[i],由于最后一个已经计算完,所以从res[A.length-2]开始
        for (int i = A.length-2;i>=0;i--){
            //temp =temp*A[i+1]; temp就是i位置对应的右边部分的值 从A[n-1]一直乘到A[1]
            temp *= A[i+1];
            res[i] *= temp;//res[i]为左边乘积*右边乘积
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值