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

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

题目描述

思路

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

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

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

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
相关推荐
longlongzihan9 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince15 小时前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
圣保罗的大教堂15 小时前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode
All for pursuit.19 小时前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
Tisfy21 小时前
LeetCode 0678.有效的括号字符串:O(n)+O(1)一次遍历
算法·leetcode·字符串·题解·贪心·括号匹配
Navigator_Z1 天前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木2 天前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.2 天前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.2 天前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用2 天前
LeetCode-560.和为 K 的子数组
算法·leetcode