1 题目描述
给定一个数组 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 解题思路
这个链接写的很好,但是现在消化不了,等有时间回来看一下
面试题66. 构建乘积数组(表格分区,清晰图解)
- 方法:头尾遍历
头尾遍历一遍就好啦,先乘左边,再乘右边
3 解决代码
class Solution {
public int[] constructArr(int[] a) {
int[] res = new int[a.length];
for(int i = 0, cur = 1; i< a.length; i++){
// 先乘左边的数(不包括自己)
res[i] = cur;
cur *= a[i];
}
for(int i = a.length - 1, cur = 1; i >= 0; i--){
// 再乘右边的数(不包括自己)
res[i] *= cur;
cur *= a[i];
}
return res;
}
}