【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
相关推荐
tankeven1 分钟前
HJ165 小红的优惠券
c++·算法
先积累问题,再逐次解决18 分钟前
快速幂优美算法
算法
xiaoshuaishuai830 分钟前
Git二分法定位Bug
开发语言·python
2401_8357925438 分钟前
FastAPI 速通
windows·python·fastapi
XiYang-DING40 分钟前
【LeetCode】 225.用队列实现栈
算法·leetcode·职场和发展
花月C1 小时前
线性动态规划(Linear DP)
算法·动态规划·代理模式
YMWM_1 小时前
export MPLBACKEND=Agg命令使用
linux·python
派大星~课堂1 小时前
【力扣-148. 排序链表】Python笔记
python·leetcode·链表
微涼5301 小时前
【Python】在使用联网工具时需要的问题
服务器·python·php