Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
Subscribe to see which companies asked this question
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> result;
int tmp = 1;
result.push_back(tmp);
for (vector<int>::const_iterator it = nums.begin(); it != nums.end() - 1; ++it)
{
tmp *= (*it);
result.push_back(tmp);
}
tmp = 1;
vector<int>::iterator it_result = result.end() - 2;
for (vector<int>::const_iterator it = nums.end() - 1; it != nums.begin(); --it)
{
tmp *= (*it);
(*it_result) *= tmp;
--it_result;
}
return result;
}
};
Personal Note:
遍历nums两次,第一次正序,计算索引i之前各数乘积并存入result,第二次反序,计算索引i之后各数乘积并与之前result相乘,得到最终result。