leetcode 238. Product of Array Except Self-数组乘积

原题链接:238. Product of Array Except Self

【思路-Java、Python】

根据Note: The output array does not count as extra space for the purpose of space complexity analysis.

我们还是可以申请大小为 n 的空间 result 用于返回结果,由于题目要求不能出现除运算,所以本题的基本思路是:

0. 申请两个大小为 n 的数组

1. 第一个数组的第 i 个元素存储第0个到第 i-1 个元素的乘积

2. 第二个数组的第 i 个元素存储第 i+1 到最后一个元素的乘积

3. 然后将两个数组的第 i 个元素和第 i 个元素相乘就能得到结果

进行优化发现其实用一个 mul 变量就可以将2数组优化为只使用1个数组

以[2,3,4]为例:

①之后 result = [1, 2, 6]

②之后 result = [12, 8, 6], mul = 24

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] result = new int[nums.length];
        result[0] = 1;
        for (int i = 1; i < nums.length; i++)  //①
            result[i] = result[i - 1] * nums[i - 1];
        for (int i = nums.length - 2, mul = nums[i+1]; i >= 0; i--) {  //②
            result[i] *= mul;
            mul *= nums[i];
        }
        return result;
    }
}
17 / 17  test cases passed. Runtime: 2 ms  Your runtime beats 46.07% of javasubmissions.
class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        result = [1] * len(nums)
        for i in range(1,len(nums)) :
            result[i] = result[i - 1] * nums[i - 1];
        mul = 1;
        for i in range(0,len(nums))[::-1] :
            result[i] *= mul
            mul *= nums[i]
        return result
17 / 17  test cases passed. Runtime: 184 ms   Your runtime beats 42.64% of pythonsubmissions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值