标签:
Given an array of n integers where n > 1, nums
,
return an array output
such thatoutput[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]
.
vector<int> productExceptSelf(vector<int>& nums) { int total=1; int num=0; int weizhi=-1; for(int i=0;i<nums.size();i++) { if(nums[i]!=0) total*=nums[i]; if(nums[i]==0) { num++; weizhi=i; } } vector<int> res(nums.size(),0); if(num>1) { return res; } else if(num==1) { res[weizhi]=total; return res; } else { for(int i=0;i<nums.size();i++) res[i]=total/nums[i]; return res; } return res; }
int n=nums.size(); vector<int> res(n,1); for(int i=0;i<n;i++) { if(i==0) res[i]=1; else res[i]=res[i-1]*nums[i-1]; } int right=1; for(int i=n-1;i>=0;i--) { res[i]*=right; right*=nums[i]; } return res;
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/47057631