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.)
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.)
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int size = nums.size();
vector<int> out(size, 1);
int product = 1;
for (int i = 1; i < size; i++) {
product *= nums[i - 1];
out[i] = product;
}
product = 1;
for (int i = size - 2; i >= 0; i--) {
product *= nums[i + 1];
out[i] *= product;
}
return out;
}
};
============= Another one ==========
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> ans(nums.size(), 1);
int i = 0, size = nums.size();
int product = 1;
while (i < size - 1) {
product *= nums[i];
ans[i + 1] = product;
i++;
}
product = 1;
while (i > 0) {
product *= nums[i];
ans[i - 1] *= product;
i--;
}
return ans;
}
};
================
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> ans(nums.size(), 1);
int prod = 1;
for (int i = 0; i < nums.size() - 1; i++) {
prod *= nums[i];
ans[i + 1] = prod;
}
prod = 1;
for (int i = nums.size() - 1; i > 0; i--) {
prod *= nums[i];
ans[i - 1] *= prod;
}
return ans;
}
};
===========
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> output(nums.size(), 1);
for (int i = 1; i < nums.size(); i++) {
output[i] = nums[i - 1] * output[i - 1];
}
vector<int> output2(nums.size(), 1);
for (int i = nums.size() - 2; i >= 0; i--) {
output2[i] = nums[i + 1] * output2[i + 1];
}
for (int i = 0; i < nums.size(); i++) {
output[i] *= output2[i];
}
return output;
// space: efficient one
/*
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> ans(nums.size(), 1);
int prod = 1;
for (int i = 0; i < nums.size() - 1; i++) {
prod *= nums[i];
ans[i + 1] = prod;
}
prod = 1;
for (int i = nums.size() - 1; i > 0; i--) {
prod *= nums[i];
ans[i - 1] *= prod;
}
return ans;
}
*/
}
};
No comments:
Post a Comment