Description
Given an array of
n
integers where 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]
.
Analysis
Avoid repeatitive multiple. Therefore, set two arrays to storage the forward or backward results. The formula is
ForwardProduct[i]={ForwardProduct[i−1]×nums[i]nums[0](i=1,...n−2)(i=0)
BackwardProduct[i]={BackwardProduct[i+1]×nums[i+1]nums[n−1](i=0,...n−3)(i=n−2)
Code
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
// pf(i):forward product from nums[0] to nums[i]
// pb(i):back product from nums[n-1] downto nums[i+1]
int n = nums.size();
vector<int> pf(n-1),pb(n-1),result;
pf[0]=nums[0];
pb[n-2]=nums[n-1];
for (int i=1;i<n-1;i++){
pf[i]=pf[i-1]*nums[i];
}
for (int i=n-3;i>=0;i--){
pb[i]=pb[i+1]*nums[i+1];
}
result.push_back(pb[0]);
for (int i=1;i<n-1;i++){
result.push_back(pf[i-1]*pb[i]);
}
result.push_back(pf[n-2]);
return result;
}
};
Appendix
- Link: https://leetcode.com/problems/product-of-array-except-self/
- Run Time: 75ms