LeetCode----Product of Array Except Self

本文提供了一种方法来解决给定数组乘积问题,即返回一个数组,其中每个元素表示原始数组中除了当前元素外的所有元素的乘积,同时确保算法的时间复杂度为O(n),不使用除法运算。

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

Product of Array Except Self

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

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

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

分析:

给定一个整型数组,返回一个结果数组,要求返回的数组的第i项表示原数组中除第i项外所有项的乘积,不使用除法,O(n)时间。

假定有数组[a1, a2, ..., ax, c, b1, b2, ... by],那么c的位置返回的应该是a1*a2*...*ax * b1*b2*... *by。

一个简单的思路:使用数组ArrayA存储由前往后,每一项存储到该项所有元素的乘积,使用数组ArrayB存储由后往前,每一项存储该项后面所有元素的乘积,最后将两个数组对应项相乘,所得的乘积数组即为结果数组。


代码:

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        nLen = len(nums)
        ans = [0] * nLen
        ans[0] = 1
        step = range(nLen)
        # 从前往后,该论循环结束后,ans数组的每一项存储该项前面所有元素的乘积
        for i in step[1:]:
            ans[i] = ans[i - 1] * nums[i - 1]
        # 由后往前,nums数组的每一项存储该项及后面所有元素的乘积
        for j in step[::-1][1:]:
            ans[j] = ans[j] * nums[j + 1]
            nums[j] = nums[j] * nums[j + 1]
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值