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.)
这道题是计算数组中除当前数字之外其他数字的乘积,题目难度为Medium。
题目限定了时间复杂度为O(n),双层遍历不能使用,同时不能用除法,因而用总乘积除以每个数字的方法也不能使用。求除了当前数字之外其他数字的乘积,我们可以把问题分解为左右两部分,分别求出左边和右边数字的乘积,然后把两个乘积相乘就得到了结果。具体代码:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> output(nums.size(), 1);
int right = 1;
for(int i=1; i<nums.size(); i++) {
output[i] = output[i-1] * nums[i-1];
}
for(int i=nums.size()-1; i>=0; i--) {
output[i] *= right;
right *= nums[i];
}
return output;
}
};