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).
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
问题分析:题目目的就是将数组对应位置的元素换位剩余位置元素的乘积。拿到此题不要固定思维,不要去想怎么从当前元素来获取其他剩余元素,而应该想到的是先将所有元素的乘积获取到,然后在除掉对应位置的元素即可。这里涉及到除法,就需要判断元素是否为零,为零的元素需要单独考虑,实际分类看如下代码:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int sum=1,count=0;
for(int i=0;i<nums.size();i++){
if(nums[i]!=0) sum*=nums[i];
else count++;
}
for(int i=0;i<nums.size();i++){
if(count==0) nums[i]=sum/nums[i];
else if(count==1){
if(nums[i]==0) nums[i]=sum;
else nums[i]=0;
}
else{
nums[i]=0;
}
}
return nums;
}
};