题目:
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.)
题意:
给定一个数组,求这样一个数组,结果数组的每一个位置上的元素,等于原数组除了该位置外其余各个位置元素的乘积。不许使用除法,不许使用额外的空间。
思路:
如果可以使用除法的话,那么只要算出所有的总的乘积,然后各自除掉各个位置上的数即可。不许使用除法的话我们考虑使用把乘法分解成两个部分。比如A[n],求res[i]时,需要求得A的0~i-1下标元素的乘积,再乘上后面部分,i+1~n-1的部分。所以我们可以分别把这两个部分都求出来。因为不需使用额外的空间,我们就使用结果值的空间以及原来数组的空间,将从前往后累成的结果保存在res中,再将从后往前乘的结果保存在A中,然后从res的后面往前面计算res[i] = res[i-1] * A[i+1]。
以上,代码如下:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int size = nums.size();
if(size <= 1)return vector<int>();
vector<int> result(size, 1);
result[0] = nums[0];
for(int i = 1; i < size; i++)
result[i] = result[i-1] * nums[i];
int tmp = result[size - 2];
for(int i = size - 2; i >= 0; i--)
nums[i] *= nums[i+1];
for(int i = size - 2; i >= 0; i--)
result[i] = result[i-1] * nums[i+1];
result[0] = nums[1];
result[size - 1] = tmp;
return result;
}
};