标签:238 leetcode c++ product of array exc
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]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
给一数组,返回一个数组,返回数组的元素i为所给数组所有元素除了元素i的乘积。
要求o(n)时间复杂度,常数空间
分三种情况:1、所给数组0的个数大于1,则输出数组所有元素为0
2、所给数组0的个数为1(nums[i]=0),输出数组除了i不为0,其他都为0
3、所给数组没有0
AC代码:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> res; int sum=nums.size(); int x=1; int sum_zero=0; int index=-1; for(int i=0; i<sum; ++i) { if(nums[i]==0) { ++sum_zero; index=i; } } if(sum_zero>1) { for(int i=0; i<sum; ++i) res.push_back(0); return res; } else if(sum_zero==1) { for(int i=0; i<sum; ++i) { if(i==index) continue; else x*=nums[i]; } for(int i=0; i<sum; ++i) { if(i==index) res.push_back(x); else res.push_back(0); } } else { for(int i=0; i<sum; ++i) x*=nums[i]; for(int i=0; i<sum; ++i) res.push_back(x/nums[i]); return res; } } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
[leetcode 238]Product of Array Except Self
标签:238 leetcode c++ product of array exc
原文地址:http://blog.csdn.net/er_plough/article/details/47342635