题目来源
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.)
这道题看到的第一想法就是先把所有相乘,然后再除以每个nums[i],然后还得处理一些特殊情况。
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
long long sum = 1;
vector<int> res;
int count0 = 0;
for (auto num : nums) {
if (num == 0) {
count0++;
continue;
}
sum *= num;
}
if (count0 > 1)
return vector<int>(nums.size(), 0);
for (auto num : nums) {
if (count0 == 0)
res.push_back(sum / num);
else {
if (num == 0)
res.push_back(sum);
else
res.push_back(0);
}
}
return res;
}
};
感觉代码写的比较乱…然后我还是想的太多,直接乘不好吗对吧…代码如下:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, 1);
for (int i=1; i<n; i++) {
res[i] = res[i-1] * nums[i-1];
}
int a = 1;
for (int i=n-1; i>0; i--) {
a *= nums[i];
res[i-1] *= a;
}
return res;
}
};