解法:左 * 右
思想:
不能用除法,那就将左边和右边分开,最终相乘

复杂度:
●时间:O(N)
●空间:O(1)
代码注意点:
left每次*的是a[i - 1]
right每次*的是a[j + 1]
不能漏掉这两个1
代码:(两次循环,可改进)
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
//多次用到a.size(),所以存起来
int size_a = a.size();
if(size_a == 0)
return {
};
vector<int>res(size_a, 1);
//left存储左边,right存储右边
int left = 1, right = 1;
for(int i = 1; i < a.size(); ++i){
left *= a[i - 1];
res[i] *= left;
}
for(int j = size_a - 2; j >= 0; --j){
right *= a[j + 1];
res[j] *= right;
}
return res;
}
};
改进代码(一次循环):
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
int size = a.size();
if(size == 0)
return {
};
vector<int>b(size, 1);
int left = 1, right = 1;
for(int i = 1; i < size; ++i){
//left从左乘
left *= a[i - 1];
b[i] *= left;
//right从右乘
right *= a[size - i];
b[size - 1 - i] *= right;
}
return b;
}
};