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.)
不能使用划分,并且时间复杂度为O(n)。
例如,给定数组元素 [1,2,3,4] ,应当返回数组 [24,12,8,6]
提高:
你的答案能保证固定的空间复杂度吗?(注意:输出的数组空间在空间复杂度计算中不算作额外空间)
这里我分了三种情况,即nums里面0的个数分别为0,1,2以上三种:当有0个0时,求所有元素的乘积,每个元素再除当前num[i]的值即可;当有1个0时,除了output[i]为所有元素除nums[i]的乘积之外,其余结果均为0;当有2个或2个以上时,所有元素均为0。不过这样做好像违反了题目中不能划分的要求。。。
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int temp=1,i=0;
int count=0,flag=0;
vector<int> ans;
for(i=0;i<nums.size();i++)
{
if(nums[i]==0)
{
count++;
flag=i;
if(count>1) break;
}
else temp*=nums[i];
}
if(count>1)
{
for(i=0;i<nums.size();i++)
ans.push_back(0);
}
else
{
for(i=0;i<nums.size();i++)
{
if(count==1)
{
if(i!=flag)
ans.push_back(0);
else ans.push_back(temp);
}
else ans.push_back(temp/nums[i]);
}
}
return ans;
}
};