leetcode 238. Product of Array Except Self #Medium
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].
先从前到后遍历数组,保存当前数字左边所有数的乘积;再从后到前遍历,保存当前数字右边所有数字的乘积;最后每个数字的左右两边的乘积再相乘
class Solution {
public:
vector
productExceptSelf(vector
& nums) {
vector
r(nums.size(),1);
for(int i=1;i
=0;i--){
r[i]*=x;
x*=nums[i];
}
return r;
}
};