日野弥生:勉強しよう

LeetCode 238 - 除自身以外数组的乘积

发表于2025年04月10日

#前缀和 #数组

题目要求不能用除法,很明显需要使用前缀和方法,不过此处应该叫前缀积。题目要求出了输出列表,仅能有O(1)的空间损耗,所以前缀积直接用结果列表存储,而反过来的后缀积则只需要一个变量存储即可。

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        result = []
        currRet = 1
        for val in nums:
            currRet *= val
            # 求前缀积
            result.append(currRet)
        
        currRevertRet = 1
        # 反过来遍历列表,求后缀积
        for index in range(len(nums) - 1, -1, -1):
            if index == 0:
                # 如果以及到列表最开头,那就直接返回后缀积即可(注意,没有包含当且数组)
                result[index] = currRevertRet
            else:
                # 返回前一个数字的前缀积和后一个数字的后缀积
                result[index] = result[index - 1] * currRevertRet
                # 运算后缀积
                currRevertRet *= nums[index]
        return result

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/product-of-array-except-self/

上一篇

LeetCode 605 - 种花问题

下一篇

LeetCode 334 - 递增的三元子序列