Given an integers array A.
Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.
Have you met this question in a real interview?
Yes
Example
For A = [1, 2, 3]
, return [6, 3, 2]
.
LeetCode上的原题,请参见我之前的博客Product of Array Except Self。
解法一:
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) {
int n = nums.size();
vector<long long> fwd(n, ), bwd(n, ), res(n);
for (int i = ; i < n - ; ++i) {
fwd[i + ] = fwd[i] * nums[i];
}
for (int i = n - ; i > ; --i) {
bwd[i - ] = bwd[i] * nums[i];
}
for (int i = ; i < n; ++i) {
res[i] = fwd[i] * bwd[i];
}
return res;
}
};
解法二:
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) {
long long n = nums.size(), right = ;
vector<long long> res(n, );
for (int i = ; i < n; ++i) {
res[i] = res[i - ] * nums[i - ];
}
for (int i = n - ; i >= ; --i) {
res[i] *= right;
right *= nums[i];
}
return res;
}
};