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

leetcode链接:https://leetcode-cn.com/problems/product-of-array-except-self/

问题描述:

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

 算法思路:

用L列表记录每个元素左边的乘积 L[i] = L[i-1] * nums[i-1],其中L[0]初始化成1。

用R列表记录每个元素右边的乘积R[i] = R[i+1] * nums[i+1],  其中R[-1]初始化成1。

最后的结果reult = L[i] * R[i]

空间复杂度o(n) 时间复杂度o(n)

代码如下:

 

# 方法1 时间o(n) 空间o(n)
def productExceptSelf(self, nums):
    L = [0]*len(nums)
    L[0] = 1
    R = [0]*len(nums)
    R[-1] = 1
    result = [0]*len(nums)
    
    for i in range(1,len(nums)):
        L[i] = L[i-1]*nums[i-1]

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

    for i in range(len(nums)):
        result[i] = L[i] * R[i]

    return result
    
# 方法2 时间o(n) 空间o(1)  
def productExceptSelf(self, nums: List[int]) -> List[int]:
    # 空间复杂度为o(n) 时间复杂度为o(n)
    L = [0]*len(nums)
        
    L[0] = 1
    R = 1
    for i in range(1,len(nums)):
        L[i] = L[i-1]*nums[i-1]
        
    for j in range(len(nums)-2,-1,-1):
        R = R*nums[j+1]
        L[j] *= R
            
    return L

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值