238. Product of Array Except Self
问题描述:
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]
.
Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
解题思路:
求数组其他元素的乘积。
我们可以从左向右乘一遍,不乘本身,从i = 1 开始乘,得到一个数组leftProduct。
再从右向左乘一遍,不乘本身,从i=nums.size()-2,得到数组rightProduct。
然后将Left和Right相乘得到最后结果。
这里我扩出去了几位用于对齐。
代码:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> ret; if(nums.empty()) return ret; vector<int> leftProduct(nums.size()+1, 1); vector<int> rightProduct(nums.size()+1, 1); for(int i = 1; i <= nums.size(); i++){ leftProduct[i] = leftProduct[i-1]*nums[i-1]; } for(int i = nums.size()-1; i > -1; i--){ rightProduct[i] = rightProduct[i+1]*nums[i]; } for(int i = 0; i < nums.size(); i++){ ret.push_back(leftProduct[i] * rightProduct[i+1]); } return ret; } };
Follow Up:
使用一个变量来记录单向乘积
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { if(nums.size() == 0){ return vector<int>(); } vector<int> ret(nums.size(), 1); //from left to right for(int i = 1; i < nums.size(); i++){ ret[i] = ret[i-1] * nums[i-1]; } //fron right to left int rightSide = 1; for(int i = nums.size() - 2; i > -1; i--){ rightSide *= nums[i+1]; ret[i] *= rightSide; } return ret; } };