Product of Array Exclude Itself
题目:
Given an integers array A.
Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.
分析:
这题目不允许用除法,就不谈了,如果可以用除法,必须要考虑有没有0的问题,其实更容易中陷阱
同时这个题目有corner case分别是nums长度为0或者为1,长度为1的情况比较容易忘记
解法:
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
if (nums.size() == 0) {
return vector<long long>();
}
vector<long long> forward(nums.size(), 1);
vector<long long> backward(nums.size(), 1);
forward[0] = nums[0];
for (int i = 1; i < nums.size(); i++) {
forward[i] = forward[i - 1] * nums[i];
}
backward[nums.size() - 1] = nums[nums.size() - 1];
for (int j = nums.size() - 2; j >= 0; j--) {
backward[j] = backward[j + 1] * nums[j];
}
vector<long long> res(nums.size(), 1);
if (nums.size() == 1) {
return res;
}
res[0] = backward[1];
res[nums.size() - 1] = forward[nums.size() - 2];
for (int i = 1; i < nums.size() - 1; i++) {
res[i] = forward[i - 1] * backward[i + 1];
}
return res;
}
};