LeetCode:238. Product of Array Except Self

LeetCode:238. Product of Array Except Self

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

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).

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

给定一个长度为n的整型数组nums,对于某个位置i,输出数组output在该位置上的元素是nums中除了i位置元素之外所有元素的乘积。求最终的output数组。

思路:乘积 = 当前数左边的乘积 * 当前数右边的乘积

以数组 [2,3,4,5]为例,以 left 数组来记录某个位置左边的所有元素乘积,以right 数组来记录某个位置右边的所有元素乘积,那么对于最终的输出结果output,里面的某个位置的元素值为output[i] = left[i] * right[i]。

Python 代码实现

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        l = len(nums)
        res = [0]*l
        left = [1]*l
        right = [1]*l
        leftProduct = 1
        rightProduct = 1
        for i in range(1,l):
            leftProduct *= nums[i-1]
            left[i] = leftProduct
            
        for i in range(0,l-1)[::-1]:
            rightProduct *= nums[i+1]
            right[i] = rightProduct
            res[i] = left[i]*right[i]
        res[l-1]=left[l-1]
        return res 

由于对空间复杂度还有要求,所以改进一下,取出left和right两个数组,直接用res数组暂存:

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        l = len(nums)
        res = [1]*l
        
        leftProduct = 1
        rightProduct = 1
        for i in range(1,l):
            leftProduct *= nums[i-1]
            res[i] = leftProduct                
        for i in range(0,l-1)[::-1]:
            rightProduct *= nums[i+1]
            res[i] = res[i]*rightProduct
        return res

THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值