238. 除自身以外数组的乘积_python

【题目】

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

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

【思路】

  1. 审题:不能使用除法和要在O(n)时间复杂度完成,说明不能用两层for循环
  2. 两个并列的for循环。
    第一个for循环:left和right两个数组储存当前值左边和右边的所有元素乘积。
    第二个for循环:将left和right相乘。

【python】

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        #nums = [1, 2, 3, 4]
        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

【结果】
在这里插入图片描述

【学习收获】
题目还有进阶选项:常数空间复杂度O(1),也就是所用空间不随n的变化而变化(除了输出数组空间res)

借鉴高手代码:https://sweets.ml/2019/03/03/leetcode-238/

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n =len(nums)
        result = [1 for i in range(n)]
        result_left = 1
        result_right = 1
        for i in range(n-1):
            result_left *=nums[i]
            result[i+1] =result_left
        for i in range(n-1,0,-1): #从n-1到1
            result_right *=nums[i]
            result[i-1] *= result_right
        return result 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值