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

题解

计算i左右两边的乘积,两边乘积再相乘,就可以了

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func productExceptSelf(nums []int) []int {
length := len(nums)
if length < 2 {
return nums
}

res := make([]int, length)
res[0] = 1
for i := 1; i < length; i++ {
res[i] = res[i - 1] * nums[i - 1]
}
reverse := 1
for i := length - 1; i >= 0; i-- {
res[i] *= reverse
reverse *= nums[i]
}

return res
}