题目
题解
题目规定了不能使用除法、这样的话i后面的数值的乘积可使用遍历了直接求出来
解法一:三指针暴力解法
这种解法是简单暴力、但时间负责度为O(n2),根据题目的数据规模10万果不其然会超时。
class Solution {
public int[] constructArr(int[] a) {
int i = 0 , j = 0, k = 1 ;
int[] res = new int[a.length];
while (j < a.length){
int pcur = 1,lcur = 1;
for (int l = i; l < j; l++) {
pcur *= a[l];
}
for (int l = k; l < a.length; l++) {
lcur *= a[l];
}
res[j] = pcur*lcur;
j++;
k++;
}
return res;
}
}
解法二:另起乘积数组
我们可以起一个数组存储从大到小的数组,这样我们只要遍历两遍数组就可以了,时间复杂度降为了O(n)、但这样就会提升空间负责度为O(n)。
class Solution {
public int[] constructArr(int[] a) {
int n = a.length;
// 数组为空时返回空数组
if (n == 0){
return new int[0];
}
int[] res = new int[n];
int[] rpro = new int[n];
rpro[n-1] = a[n-1];
for (int i = n-2; i >= 0; i--) {
rpro[i] = a[i]*rpro[i+1];
}
int s = 1;
for (int i = 0; i < n; i++) {
if (i != n-1){
res[i] = s*rpro[i+1];
}else {
res[i] = s;
}
s *= a[i];
}
return res;
}
}