238. Product of Array Except Self (M)

本文介绍了一种在O(n)时间复杂度内解决数组产品问题的方法,即求解除自身外数组中所有元素的乘积。通过两次遍历,首先计算每个元素左侧所有元素的乘积,然后计算每个元素右侧所有元素的乘积,最终得到目标数组。此方法避免了使用除法运算,同时达到了O(1)的空间复杂度。

Product of Array Except Self (M)

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)


题意

给定一个数组nums,要求返回一个新数组output,满足以下条件:
output[i]=∏j≠inums[j] output[i] = \prod_{j\not=i}nums[j] output[i]=j=inums[j]
限制时间复杂度为O(N)O(N)O(N),且不能使用除法。

思路

output[i]相当于在nums中将nums[i]左边所有数和nums[i]右边所有数累乘。因此可以采取类似于动态规划的操作:先从左到右遍历一遍nums,记录当前位置所有左侧数字之积;再从右到左遍历一遍nums,记录当前位置所有右侧数字之积,将两者相乘后得到的就是output。可以只使用一个output数组来达到O(1)O(1)O(1)的空间复杂度。

0123
nums1234
左右遍历1126
右左遍历241241
Output241286

代码实现

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

        int leftProduct = 1;
        for (int i = 0; i < nums.length; i++) {
            output[i] = i == 0 ? 1 : (leftProduct *= nums[i - 1]);
        }

        int rightProduct = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            output[i] = output[i] * (i == nums.length - 1 ? 1 : (rightProduct *= nums[i + 1]));
        }

        return output;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值