题目描述
给定一个数组 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]。不能使用除法。
示例:
输入: [1,2,3,4,5]
输出: [120,60,40,30,24]
提示:
所有元素乘积之和不会溢出 32 位整数
a.length <= 100000
方法
1.暴力法
思路
针对每个数组中每个位置的值,用一个循环遍历累乘,得出结果。
时间复杂度O(n^2)
代码
public int[] constructArr(int[] a) {
int[] res = new int[a.length];
for(int i=0; i<a.length; i++){
int dot = 1;
for(int j=0; j<a.length; j++){
if(i==j) continue;
dot *= a[j];
}
res[i] = dot;
}
return res;
}
2.表格法
参考链接
https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/
思路
采用填表的策略,结果数组等于表中每一行元素的乘积。通过分别求出下三角和上三角的的累乘,将时间复杂度降至O(n)。在求解累乘时,使用了前面累乘值的结果,类似于dp的策略,充分利用了前面计算结果的信息,降低时间复杂度。具体的地举例 B [ 2 ] = B [ 1 ] ∗ A [ 1 ] B[2]=B[1]*A[1] B[2]=B[1]∗A[1]
总结来说,在面对数组,面对累乘的问题时,要思考可以不可以用前面已计算的结果来进行优化。可不可以用表格的思路。
代码
实现部分,我看了大佬的思路,自己写简陋的代码
public int[] constructArr(int[] a) {
// 空值处理
if (a.length == 0)
return new int[0];
int[] res = new int[a.length];
// 填左下角的表格
res[0] = 1;
int temp = 1; // 累乘值1
for (int i = 1; i < a.length; i++) {
temp *= a[i-1];
res[i] = temp;
}
// 填右上角表格
int acc = 1; // 累乘值2
for (int j = a.length - 2; j >= 0; j--) {
acc *= a[j+1];
res[j] *= acc;
}
return res;
}