LeetCode-剑指66-构建乘积数组

在这里插入图片描述

1、左右数组积

考虑到我们不能使用除法,我们可以对当前第 i i i行的第 i i i个元素左右的数组进行求积,而后将左右两侧的积相乘即可。时间和空间复杂度为 O ( n ) O(n) O(n)

class Solution {
public:
    vector<int> constructArr(vector<int> &a) {
        int n = a.size();
        vector<int> dp1(n, 1), dp2(n, 1), res(n);
        for (int i = 1; i < n; ++i) {
            dp1[i] = dp1[i - 1] * a[i - 1];
            dp2[n - 1 - i] = dp2[n - i] * a[n - i];
        }
        for (int i = 0; i < n; ++i) {
            res[i] = dp1[i] * dp2[i];
        }
        return res;
    }
};

2、左右数组积优化

考虑到实际上在每次循环中我们并不会使用到数组中的每一个元素,因此我们可以对该方法的空间复杂度进行优化。我们可以使用左侧数组积来代替最终结果,使用一个变量循环来代替右侧的数组积与左侧数组积相乘即可。最终的空间复杂度为 O ( 1 ) O(1) O(1)

class Solution {
public:
    vector<int> constructArr(vector<int> &a) {
        int n = a.size(), temp_product = 1;
        vector<int> res(n, 1);
        for (int i = 1; i < n; ++i) {
            res[i] = res[i - 1] * a[i - 1];
        }
        for (int i = n - 1; i >= 0; --i) {
            res[i] *= temp_product;
            temp_product = temp_product * a[i];
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值