JZ51 构建乘积数组
2021-06-05 00:03
标签:i+1 个数 rgb tip ret size -- nbsp make 构建乘积数组 B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1] JZ51 构建乘积数组 标签:i+1 个数 rgb tip ret size -- nbsp make 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/14642188.html
b[0]
1
A[1]
A[2]
A[n - 1]
b[1]
A[0]
1
A[2]
A[n - 1]
.......
A[0]
A[1]
A[2]
A[n - 1]
b[n - 2]
A[0]
A[1]
1
A[n - 1]
b[n - 1]
A[0]
A[1]
A[2]
1
从左到右算B[i]=A[0]*A[1]*...*A[i-1]
从右到左算B[i]*=A[i+1]*...*A[n-1]func multiply(a []int) []int {
if len(a) 1 {
return a
}
size := len(a)
left, right := make([]int, size), make([]int, size)
left[0] = 1
for i := 1; i {
left[i] = left[i - 1] * a[i - 1]
}
right[size - 1] = 1
for i := size - 2; i >= 0; i--{
right[i] = right[i + 1] * a[i + 1]
}
b := make([]int, size)
for i := 0; i {
b[i] = left[i] * right[i]
}
return b
}
下一篇:安装Python3.7的步骤