LeetCode-Python-238. 除自身以外数组的乘积

本文介绍了一种算法,用于计算给定数组中除当前元素外所有其他元素的乘积,不使用除法,并在O(n)时间内完成。文章提供了两种解决方案,一种使用额外的left和right数组,另一种仅使用常数空间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]

说明: 不要使用除法,且在 O(n) 时间复杂度内完成此题。

进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)

第一种思路:

不能用除法,那只能用乘法统计其他元素的乘积了,

一共扫两趟,

第一趟从左往右走,开一个数组叫left记录除第一个元素外,其他每个元素的所有左边元素的乘积,left[0] = 1

比如对于[1,2,3,4],我们有left = [1,1, 2, 6],

类似的,第二趟从右往左走,开right数组记录所有右边元素的乘积,right[-1] = 1

比如对于[1,2,3,4],我们有right = [24, 12, 4, 1]

最后把left和right对位相乘,就是需要的结果。

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        l = len(nums)
        if l == 0: 
            return nums
        left = [1] * l 
        right = [1] * l
        
        for i in range(l):
            if i == 0:
                continue
            else:
                left[i] = left[i - 1] * nums[i - 1]
                
        for i in range(l - 1, -1, -1):
            if i == l - 1:
                continue
            else:
                right[i] = right[i + 1] * nums[i + 1]
        
        res = [0] * l
        for i in range(l):
            res[i] = left[i] * right[i]
            
        return res

下面的写于2019年8月16日20:32:49:

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        left, right = [1] * len(nums), [1] * len(nums)
        
        for i in range(1, len(nums)):
            left[i] = left[i - 1] * nums[i - 1]
        for i in range(len(nums) - 2, -1, -1):
            right[i] = right[i + 1] * nums[i + 1]
        
        for i in range(len(nums)):
            nums[i] = left[i] * right[i]
        return nums

 

第二种思路:

学习自答案,O(1)的空间就可以实现。

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        d=[1]*len(nums)
        for i in range(1,len(nums)):
            d[i]=d[i-1]*nums[i-1]
        p=1
        for i in reversed(range(len(nums))):
            d[i]=d[i]*p
            p=p*nums[i]
        return d

下面的写于2019年8月16日20:49:35

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = [1] * len(nums)
        for i in range(1, len(nums)):
            res[i] = res[i - 1] * nums[i - 1]
        tmp = 1
        for i in range(len(nums) - 1, -1, -1):
            res[i] *= tmp
            tmp *= nums[i]
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值