【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
相关推荐
米粒16 小时前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
IAUTOMOBILE7 小时前
Python 流程控制与函数定义:从调试现场到工程实践
java·前端·python
Fuxiao___7 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
Mr_Xuhhh8 小时前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
漫随流水8 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
TT_44198 小时前
python程序实现图片截图溯源功能
开发语言·python
小陈的进阶之路9 小时前
logging 日志模块笔记
python
cqbelt9 小时前
Python 并发编程实战学习笔记
笔记·python·学习
穿条秋裤到处跑9 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
智算菩萨9 小时前
【论文复现】Applied Intelligence 2025:Auto-PU正例无标签学习的自动化实现与GPT-5.4辅助编程实战
论文阅读·python·gpt·学习·自动化·复现