Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
思路:
这道题我开始以为会有非常大的数出现作为一个难点,但是并没有;这道题的难点在于解决0元素的问题,我们这里分三种情况讨论:
1 没有0元素,这个时候我们只需要按照常规的用累乘除以目标数就可以了
2 有1一个0元素,这个时候除了0元素的位置,其他的数应该都是0
3 有2个及以上的0元素,这个时候所有位置的元素最后都会变成0
代码如下:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int product = 1;
int zeroCount = 0;
for (int num : nums) {
if (num == 0) zeroCount++;
else product *= num;
}
if (zeroCount > 1) return vector<int>(nums.size(), 0);
if (zeroCount > 0) {
for (int& num : nums) {
if (num == 0) num = product;
else num = 0;
}
}
else {
for (int& num : nums) num = product / num;
}
return nums;
}
};