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

1、题目描述

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

数据保证数组 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
相关推荐
PC2005-cloud13 分钟前
FinalShell 自定义背景图片教程
ide·python·pycharm
傻啦嘿哟9 小时前
某短视频平台视频爬虫实战:抓取推荐流视频信息,绕过反爬的3种技巧
开发语言·爬虫·python
迷迭香yy9 小时前
集合竞价数据挖掘实战:用Python构建开盘信号识别系统
人工智能·python·数据挖掘
小程故事多_8010 小时前
从A2C、TRPO、PPO到GRPO,强化学习策略梯度算法完整演进与大模型落地实战解析
人工智能·算法
2601_9561219712 小时前
二分算法(知识点+题目)
c++·算法
李昊哲小课12 小时前
fastapi sse websocket 奶茶店实时订单看板
人工智能·python·websocket·网络协议·fastapi·sse
2401_8445829514 小时前
工具包:软件架构设计的实用技巧与经验分享
python
RFID固定资产管理系统14 小时前
适配媒体行业的固定资产管理软件有哪些功能与核心优势
大数据·人工智能·python·媒体
AndrewHZ14 小时前
【LLM技术全景】阶段总结:技术原理篇核心知识回顾
人工智能·深度学习·算法·语言模型·大模型·llm·芯片开发
SunnyDays101114 小时前
Python 为 PowerPoint 添加动画:进入、退出、动作路径与文本动画(详解)
python·powerpoint·动画·动画效果·文本动画