27 lines
921 B
Java
27 lines
921 B
Java
# 66. 构建乘积数组
|
||
|
||
## 题目链接
|
||
|
||
[NowCoder](https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13\&tqId=11204\&tPage=1\&rp=1\&ru=/ta/coding-interviews\&qru=/ta/coding-interviews/question-ranking\&from=cyc\_github)
|
||
|
||
## 题目描述
|
||
|
||
给定一个数组 A\[0, 1,..., n-1],请构建一个数组 B\[0, 1,..., n-1],其中 B 中的元素 B\[i]=A\[0]\*A\[1]\*...\*A\[i-1]\*A\[i+1]\*...\*A\[n-1]。要求不能使用除法。
|
||
|
||
\
|
||
|
||
|
||
## 解题思路
|
||
|
||
```java
|
||
public int[] multiply(int[] A) {
|
||
int n = A.length;
|
||
int[] B = new int[n];
|
||
for (int i = 0, product = 1; i < n; product *= A[i], i++) /* 从左往右累乘 */
|
||
B[i] = product;
|
||
for (int i = n - 1, product = 1; i >= 0; product *= A[i], i--) /* 从右往左累乘 */
|
||
B[i] *= product;
|
||
return B;
|
||
}
|
||
```
|