leetcode 热题 100_除自身以外数组的乘积

题解一:

        前缀 / 后缀数组:某元素除自身以外的乘积,也就是其全部前缀元素乘积 * 全部后缀元素乘积,因此我们可以构造前缀数组和后缀数组,分别存储前i个元素的成绩和后i个元素的乘积,再将i-1前缀乘积 * i+1后缀乘积得到结果并用新数组存储。

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] left = new int[n];
        int[] right = new int[n];
        int[] result = new int[n];
        left[0] = nums[0];
        right[n - 1] = nums[n - 1];

        for (int i = 1; i < n; i++) {
            left[i] = left[i - 1] * nums[i];
        }
        for (int i = n - 2; i >= 0; i--) {
            right[i] = right[i + 1] * nums[i];
        }

        result[0] = right[1];
        result[n - 1] = left[n - 2];
        for (int i = 1; i < n - 1; i++) {
            result[i] = left[i - 1] * right[i + 1];
        }

        return result;
    }
}

题解二:

        O(1)空间复杂度解法:题目规定输出数组不视为额外空间,因此可以直接在输出数组进行前缀数组和后缀数组的计算,先从左到右计算前缀数组,再从右到左直接将后缀数组乘入前缀数组。需要注意边界值的处理。

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];

        int pre = nums[0];
        for (int i = 1; i < n; i++) {
            result[i] = pre;
            pre *= nums[i];
        }

        result[0] = 1;
        int after = nums[n - 1];
        for (int j = n - 2; j >= 0; j--) {
            result[j] = result[j] * after;
            after *= nums[j];
        }

        return result;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值