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。

本文详细介绍了如何通过遍历数组两次来解决给定问题,即返回一个数组,使得数组中每个元素为原始数组中除了自身以外的所有元素的乘积。解决方案避免了使用除法操作,并且运行时间为O(n),空间复杂度为O(1),不计入输出数组的空间。文章还讨论了进阶问题,即是否能在常数空间复杂度下解决问题。
1450

被折叠的 条评论
为什么被折叠?



