题目:
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
这道题本身不难,难点主要在于要求不使用除法,并且时间和空间要求O(N).
主要思路就是采用一次正向扫描和一次反向扫描来求。
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int>product(nums.size(), 1);
for(auto i = 1; i < nums.size(); i++)
product[i] = nums[i-1] * product[i - 1];
int right = 1;
for(int i = nums.size() - 2; i >= 0; i--)
{
right *= nums[i + 1];
product[i] = product[i] * right;
}
return product;
}
};