剑指 Offer 66. 构建乘积数组
难度:中等
给定一个数组 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
解答:
class Solution {
//两次遍历
//时间复杂度O(N),空间复杂度O(1)
public int[] constructArr(int[] a) {
int len = a.length;
if(len <= 0) return new int[0];
int[] ans = new int[len];
ans[0] = 1;
int temp = 1;
for(int i = 1; i < len; i++){
ans[i] = ans[i - 1] * a[i - 1];
}
for(int i = len - 2; i >= 0; i--){
temp = temp * a[i + 1];
ans[i] *= temp;
}
return ans;
}
}
参考自:
作者:LeetCode-Solution
链接: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/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。