leetcode hot100 238.除了自身以外数组的乘积 medium

暴力解法,会超出时间:

时间复杂度O(n²)

python 复制代码
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        if not nums:
            return []

        res = [1] * len(nums)  # 初始化 res 数组,所有值为 1

        for i in range(len(nums)):
            plus = nums[:]
            plus[i] = 1
            for p in plus:
                res[i] *= p

        return res
python 复制代码
plus = nums[:]    # 使用切片操作创建 nums 的副本
plus = nums 	  # 引用传递,意味着 plus 变量只是对 nums 的引用(它们指向同一个内存位置),当修改 plus[i] 时,实际上是在修改 nums[i],因为 plus 和 nums 共享相同的内存空间。

和接雨水有点像

先算左边的乘积,

再算右边的乘积

暴力:

left 和 right 都是 时间复杂度O(n²)

res 数组的时间复杂度是 O(n)

O(n²)+O(n²)+O(n)=O(n²)

空间复杂度是 O(n)

使用了三个数组 left、right 和 res,它们的大小都为 n

python 复制代码
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        if not nums:
            return []

        n = len(nums)

        left = [1] * n
        for i in range(n):
            for j in range(0,i):
                left[i] *= nums[j]


        right = [1] * n
        for i in range(n):
            for j in range(i+1,n):
                right[i] *= nums[j]
        
        res =  [1] * n
        for i in range(n):
            res[i] =  left[i] * right[i]

        return res

可以通过 前缀乘积 和 后缀乘积 的方法将时间复杂度从 O(n²) 优化到 O(n)

python 复制代码
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        if not nums:
            return []

        n = len(nums)

        res = [1]*n

        #  计算前缀乘积
        left = 1
        for i in range(n):
            res[i] = left       # 前缀乘积
            left *= nums[i]   # 更新前缀乘积

        right = 1
        for i in range(n-1, -1 ,-1):
            res[i] *= right       # 后缀乘积
            right *= nums[i]   # 更新后缀乘积

        return res

或者

python 复制代码
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        if not nums:
            return []

        n = len(nums)

        #  计算前缀乘积
        left = [1]*n
        for i in range(1,n):
           left[i] = left[i - 1] * nums[i - 1]

        right = [1] * n  # 初始化 right 数组
        for i in range(n - 2, -1, -1):  # 从倒数第二个元素开始
            right[i] = right[i + 1] * nums[i + 1]

        # Step 3: 计算结果数组 res
        res = [1] * n
        for i in range(n):
            res[i] = left[i] * right[i]

        return res
相关推荐
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll6 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐6 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶6 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER6 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了6 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333337 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录7 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1237 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode