forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT51.java
More file actions
31 lines (30 loc) · 829 Bytes
/
T51.java
File metadata and controls
31 lines (30 loc) · 829 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package web; /**
* @program LeetNiu
* @description: 构建乘积数组
* @author: mf
* @create: 2020/01/16 14:01
*/
/**
* 给定一个数组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]。
* 不能使用除法。
*/
public class T51 {
public int[] multiply(int[] A) {
int length = A.length;
int[] B = new int[length];
if (length != 0) {
B[0] = 1;
// 计算下三角连乘
for (int i = 1; i < length; i++) {
B[i] = B[i - 1] * A[i - 1];
}
int temp = 1;
// 计算上三角
for (int j = length - 2; j >= 0; j--) {
temp *= A[j + 1];
B[j] *= temp;
}
}
return B;
}
}