Appearance
66-构建乘积数组
题目描述
https://leetcode.cn/problems/gou-jian-cheng-ji-shu-zu-lcof
给定一个数组 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
思路分析
不能使用除法 对于 i 位置的数,应该是 [0..i-1] 的乘积乘以 [i+1..n-1] 的乘积,所以我们用两个数组直接保存从左往右的乘积和从后往左的乘积 然后 遍历 i 使用i两边的乘积相乘即为结果
实现代码
csharp
public class Solution {
public int[] ConstructArr(int[] a) {
int n = a.Length;
if(n == 0){
return new int[]{};
}
int temp = 1;
int[] left = new int[n];
for(int i=0; i < n; i++){
temp *= a[i];
left[i] = temp;
}
temp = 1;
int[] right = new int[n];
for(int j=n-1; j>=0; j--){
temp *= a[j];
right[j] = temp;
}
//计算结果
int[] result = new int[n];
for(int i=0; i<n; i++){
if(i == 0){
result[i] = right[i+1];
}
else if(i == n-1){
result[i] = left[i-1];
}
else{
result[i] = left[i-1] * right[i+1];
}
}
return result;
}
}
优化代码
直接从左往右,在从右往左乘积计算出结果
csharp
public class Solution {
public int[] ConstructArr(int[] a) {
int n = a.Length;
if(n == 0){
return new int[]{};
}
int temp = 1;
int[] result = new int[n];
for(int i=0; i<n; i++){
result[i] = temp;
temp*=a[i];
}
temp = 1;
for(int i=n-1; i>=0; i--){
result[i] *= temp;
temp*=a[i];
}
return result;
}
}
AlgoPress