您的位置:首页 > 其它

[238]Product of Array Except Self

2015-10-14 19:02 471 查看
【题目描述】

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]
.
【思路】

先遍历所有的元素,求除了0之外的元素之积,并记录下0元素的个数和位置。

然后再重新遍历所有元素,分类讨论,如果0元素个数大于1,那么不管当前元素是否为0,其他元素里必有0,那么其积必为0;如果0元素个数正好为1,那么判断当前元素是否为0元素,是的话则其求的值即为前面遍历所有元素求得的积,不是0元素的话所求的积即为0;如果0元素个数为0,那么每个元素所求的积都只要把前面遍历求得的总积除以当前元素的值就可以了。

【代码】

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> ans;
int n=1;
int cnt=0;
int pos;
for(int i=0;i<nums.size();i++){
if(nums[i]==0){
pos=i;
cnt++;
continue;
}
n*=nums[i];
}
for(int i=0;i<nums.size();i++){
if(cnt>=2){
ans.push_back(0);
}
else if(cnt==1){
if(pos==i) ans.push_back(n);
else ans.push_back(0);
}
else ans.push_back(n/nums[i]);
}
return ans;
}
};

再贴一个discuss里看到的解法,比我的要巧妙。
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> ret (nums.size(), 1);
for(int i = 1; i < nums.size(); i++)
ret[i] *= nums[i - 1] * ret[i - 1];
int tmp = 1;
for(int i = nums.size() - 2; i >= 0; i--) {
tmp *= nums[i + 1];
ret[i] *= tmp;
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: