238 - 除自身以外数组的乘积 - python

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

示例:

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

提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。

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


如果不考虑时间复杂度,暴力法可以简单的求解

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        if not nums: return []
        
        res = []
        for i in range(len(nums)):
            others = nums[:i] + nums[i + 1:]
            ans = 1
            for n in others:
                ans *= n

            res.append(ans)
            
        return res

正确的方法是构建左、右乘积数组,两个数组的构建是线性时间复杂度,最后元素相乘仍然是线性时间复杂度,满足要求。

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        
        length = len(nums)
        L, R = [1] * length, [1] * length
        res = []
        for i in range(1, length):
            L[i] = nums[i - 1] * L[i - 1]

        for i in range(length - 2, -1, -1):
            R[i] =  nums[i + 1]* R[i + 1]       

        for i, j in zip(L, R):
            res.append(i * j)

        return res

发布了448 篇原创文章 · 获赞 122 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/Forlogen/article/details/105465201
今日推荐