leetcode 238. 除自身以外数组的乘积 (python)

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

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        ln =len(nums)
        left,right = [1]*ln,[1]*ln
        for i in range(1,ln):
            left[i] = left[i-1]*nums[i-1] #left = [1, 1, 2, 6]
            right[ln-i-1] = right[ln-i]*nums[ln-i] #right = [24, 12, 4, 1]
        res = [1]*ln
        for i in range(ln):
            res[i] = left[i]*right[i]
        return res

参考:https://blog.csdn.net/weixin_43399785/article/details/88190888 

猜你喜欢

转载自www.cnblogs.com/xiaotongtt/p/11317880.html