【leetcode100】除自身以外数组的乘积

1、题目描述

给你一个整数数组 nums,返回数组answer,其中 answer[i]等于nums中除nums[i]之外其余各元素的乘积 。

数据保证数组 nums之中任意元素的全部前缀元素和后缀的乘积都在32位整数范围内。

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

示例 1:

复制代码
输入: nums = [1,2,3,4]
输出: [24,12,8,6]

2、初始思路

2.1 思路

任意一个数除自身外所有数的乘积=该数前所有数的乘积 * 该数后所有数的乘积

复制代码
class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        mul_1 = []
        mul_2 = []
        result = []
        a = 1
        b = 1
        c = 1
        n = len(nums)
        for i in range(n):
            a *= nums[i]
            mul_1.append(a)
        nums = nums[::-1]
        for i in range(n):
            b *= nums[i]
            mul_2.append(b)
        """ print(mul_1)
        print(mul_2) """
        nums = nums[::-1]
        mul_2 = mul_2[::-1]
        for i in range(n):
            if i==0:
                result.append(mul_2[1])
            elif i==n-1:
                result.append(mul_1[-2])
            else:
                c = mul_1[i-1] * mul_2[i+1]
                result.append(c)
        return result 

2.2 缺点

时间复杂度为O(n),但运行时间很长。

3 优化算法

3.1 思路

不需要一开始就生成两个乘积列表,可以在运算过程中保留结果。

复制代码
class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        
        # 初始化结果数组
        result = [1] * n
        
        # 计算左侧乘积
        left_product = 1
        for i in range(n):
            result[i] *= left_product
            left_product *= nums[i]
        
        # 计算右侧乘积
        right_product = 1
        for i in range(n-1, -1, -1):
            result[i] *= right_product
            right_product *= nums[i]
        
        return result
相关推荐
风逸hhh6 分钟前
python打卡day58@浙大疏锦行
开发语言·python
烛阴1 小时前
一文搞懂 Python 闭包:让你的代码瞬间“高级”起来!
前端·python
JosieBook1 小时前
【Java编程动手学】Java中的数组与集合
java·开发语言·python
Gyoku Mint2 小时前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
葫三生3 小时前
如何评价《论三生原理》在科技界的地位?
人工智能·算法·机器学习·数学建模·量子计算
拓端研究室5 小时前
视频讲解:门槛效应模型Threshold Effect分析数字金融指数与消费结构数据
前端·算法
随缘而动,随遇而安7 小时前
第八十八篇 大数据中的递归算法:从俄罗斯套娃到分布式计算的奇妙之旅
大数据·数据结构·算法
郭庆汝8 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
IT古董8 小时前
【第二章:机器学习与神经网络概述】03.类算法理论与实践-(3)决策树分类器
神经网络·算法·机器学习
Alfred king10 小时前
面试150 生命游戏
leetcode·游戏·面试·数组