34 lines
1.1 KiB
Java
34 lines
1.1 KiB
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]。要求不能使用除法。
|
||
|
||
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4240a69f-4d51-4d16-b797-2dfe110f30bd.png" width="250px"> </div><br>
|
||
|
||
|
||
## 解题思路
|
||
|
||
```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;
|
||
}
|
||
```
|
||
|
||
|
||
|
||
|
||
|
||
|
||
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|