​剑指offer解法汇总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

输入:

[1,2,3,4,5]

返回值:

[120,60,40,30,24
]

解析:

既然不能除的话,那我们肯定不能每次都去乘,但是可以缓存每次计算的结果。

这样每种情况只会计算一次,长度为5的话总共会计算10种结果。时间复杂度为O(n)


代码:

public class Solution66 {

    HashMap<Integer, Integer> startCacheMap = new HashMap<>();
    HashMap<Integer, Integer> endCacheMap = new HashMap<>();

    public int[] multiply(int[] A) {
        int n = A.length;
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            Integer startValue = startCacheMap.get(i - 1);
            if (startValue == null) {
                startValue = getMuleValue(true, i - 1, A);
            }
            Integer endValue = endCacheMap.get(i + 1);
            if (endValue == null) {
                endValue = getMuleValue(false, i + 1, A);
            }
            result[i] = startValue * endValue;
        }
        return result;
    }

    private int getMuleValue(boolean isStart, int k, int[] ints) {
        int result = 1;
        if (isStart) {
            for (int i = 0; i <= k; i++) {
                result = result * ints[i];
            }
        } else {
            for (int i = k; i < ints.length; i++) {
                result = result * ints[i];
            }
        }
        return result;

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值