题目:构建乘积数组
题目描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]XA[1]X…*A[i-1]XA[i+1]X…XA[n-1]。不能使用除法。
解题思路:
B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1] 将B[I] 拆分为两部分:
(1) down[I]=A[0]XA[1]X…*A[i-1]=down[I-1]*A[I-1]; 从上往下遍历
(2) up[I]=A[i+1]X…XA[n-1] =up[I+1]A[I+1] 从下向上遍历
ps:图片来源于剑指 offer评论区
代码实现:
import java.util.ArrayList;
import java.util.;
public class Solution {
public int[] multiply(int[] A) {
int len = A.length;
// 定义下三角:down[i]=down[i+1]*A[i+1]
int[] up = new int[len];
up[len - 1] = 1;
for (int i = len - 2; i >= 0; i–) {
up[i] = up[i + 1] * A[i + 1];
}
//System.out.println(Arrays.toString(up));
// 定义下三角:down[i]=down[i-1]*A[i-1]
int[] down = new int[len];
down[0] = 1;
for (int i = 1; i < len; i++) {
down[i] = down[i - 1] * A[i - 1];
}
//System.out.println(Arrays.toString(down));
int[] res = new int[len];
for (int i = 0; i < len; i++) {
res[i] = up[i] * down[i];
}
return res;
}
}