【Golang】LeetCode 238. 除了自身以外数组的乘积

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

题目描述

思路

我们可以通过建立两个数组,以O(n)O(n)O(n)的时间复杂度来解决这个问题。

具体来说,题目中要求我们求出当前数组当中除了自身以外的乘积,我们可以建立两个数组lmulrmul,分别用于统计除了自身之外左侧数组的乘积与右侧数组的乘积(前缀积与后缀积)。

最后在统计答案时,将两部分乘积进行相乘,即可得到最终的结果。

Golang 题解

go 复制代码
func productExceptSelf(nums []int) []int {
    n := len(nums)
    lmul, rmul := make([]int, n), make([]int, n)

    lmul[0], rmul[n - 1] = 1, 1
    for i := 1; i < n; i ++ {
        lmul[i] = lmul[i - 1] * nums[i - 1]
    }
    for i := n - 2; i >= 0; i -- {
        rmul[i] = rmul[i + 1] * nums[i + 1]
    }

    ans := make([]int, n)
    for i := 0; i < n; i ++ {
        ans[i] = lmul[i] * rmul[i]
    }
    return ans
}

Python 题解

python 复制代码
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        lmul, rmul = [1] * n, [1] * n

        for i in range(1, n):
            lmul[i] = lmul[i - 1] * nums[i - 1]
        for i in range(n - 2, -1, -1):
            rmul[i] = rmul[i + 1] * nums[i + 1]
        
        ans = [1] * n
        for i in range(0, n):
            ans[i] = lmul[i] * rmul[i]
        return ans
相关推荐
yyds_yyd_1008614 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
lueluelue471 天前
LeetCode:链表
算法·leetcode·链表
橘子汽水1681 天前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
Re.不晚1 天前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
青山木1 天前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
星轨初途1 天前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode
雪碧聊技术2 天前
力扣 72. 编辑距离——动态规划经典例题
算法·leetcode·动态规划
木井巳2 天前
【DFS解决floodfill算法】岛屿的最大面积
java·算法·leetcode·深度优先
Tisfy2 天前
LeetCode 1406.石子游戏 III:递归(DFS+记忆化) / 递推(DP+原地滚动)
leetcode·游戏·深度优先·dfs·题解·博弈
yyds_yyd_100862 天前
877. 石子游戏(2026.08.02)& 486. 预测赢家(2026.08.01)
c++·leetcode