思想:
对于结果数组中的每一个元素,分别先乘以其左边的元素,然后再乘以其右边的元素.
代码:
class Solution {
public:
/**
* @param A: Given an integers array A
* @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
*/
vector<long long> productExcludeItself(vector<int> &nums) {
// write your code here
vector<long long> proc;
long long tmp = 1;
int len = nums.size();
// proc[i]中存储了i左边的乘积
for(int i = 0; i < len; ++i){
proc.push_back(tmp);
tmp *= nums[i];
}
tmp = 1;
// proc[i]继续乘以i右边的乘积
for(int i = len - 1; i >= 0; --i){
proc[i] *= tmp;
tmp *= nums[i];
}
return proc;
}
};
致谢: