提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目描述
给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程
解题思路
规律:
按照上三角和下三角的求法,参考题解: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/
class Solution {
public int[] constructArr(int[] a) {
if(a.length == 0){
return new int[0];
}
int temp = 1;
int[] b = new int[a.length];
b[0] = 1;
//计算下三角
for(int i = 1; i < a.length; i++){
b[i] = b[i - 1] * a[i - 1];
}
for(int i = a.length - 2; i >= 0; i--){
temp = temp * a[i + 1];//上三角
b[i] = b[i] * temp;//下三角*上三角
}
return b;
}
}
补充解法:找规律
class Solution {
public int[] constructArr(int[] a) {
if(a.length == 0){
return new int[0];
}
int multi = 1;
int [] pre = new int[a.length];
pre[0] = a[0];
int [] post = new int[a.length];
post[0] = a[a.length - 1];
for(int i = 1; i < a.length; i++){
pre[i] = pre[i - 1] * a[i];
post[i] = post[i - 1] * a[a.length - 1 - i];
}
int [] b = new int[a.length];
b[0] = post[post.length - 1 - 1];
for(int i = 1; i < b.length - 1; i++){
b[i] = pre[i - 1] * post[b.length - 2 - i];
}
b[b.length - 1] = pre[a.length - 1 - 1];
return b;
}
}
总结
暂时没有总结,待续。。。