题目描述
给定一个数组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
B[i] = A[0] * A[1] * A[2] * …… * A[i-1] * A[i+1] * A[i+2] * …… * A[n-1]
将上述式子分成前后两部分:B[i] = left[i] * right[i]
left[i] = A[0] * A[1] * A[2] * …… * A[i-1] = left[i-1] * A[i-1]
right[i] = A[i+1] * A[i+2] * …… * A[n-1] = right[i+1] * A[i+1]
代码1
class Solution {
public:
vector<int> multiply(const vector<int>& A) {
int len = A.size();
vector<int> left(len, 1);
vector<int> right(len, 1);
vector<int> B(len, 0);
for (int i = 1; i < len; ++i)
left[i] = left[i-1] * A[i - 1];
for (int i = len-2; i >= 0; --i)
right[i] = right[i+1] * A[i + 1];
for (int i = 0; i < len; ++i)
B[i] = left[i] * right[i];
return B;
}
};
思路2
思路tql。
代码2
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n=nums.size();
int left=1,right=1; //left:从左边累乘,right:从右边累乘
vector<int> res(n,1);
for(int i=0;i<n;++i) //最终每个元素其左右乘积进行相乘得出结果
{
res[i]*=left; //乘以其左边的乘积
left*=nums[i];
res[n-1-i]*=right; //乘以其右边的乘积
right*=nums[n-1-i];
}
return res;
}
};