问题描述:
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).
示例
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.)
问题分析:
对于第i个元素,我们考虑把前i - 1项的积sum1[i]和后n - i 项的积sum2[i]先算出来,则output[i] = sum1 * sum2.
过程详见代码:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res = nums;
int sum = res[0];
nums[0] = 1;
for (int i = 1; i < res.size(); i++)
{
nums[i] = sum;
sum *= res[i];
}
sum = 1;
int t;
for (int i = res.size() - 1; i >= 0;i--)
{
t = sum;
sum *= res[i];
res[i] = nums[i] * t;
}
return res;
}
};