# int32bit / leetcode

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
solve.cpp

## Product of Array Except Self

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.)

## Solution

```vector<int> productExceptSelf(vector<int>& nums) {
if (nums.empty()) // 空
return vector<int>();
if (nums.size() == 1) { //只有一个元素，返回{0}
return vector<int>({0});
}
auto n = nums.size();
vector<int> a(n, 1), b(n, 1);
for (auto i = 1; i < n; ++i) {
a[i] = a[i - 1] * nums[i - 1];
b[i] = b[i - 1] * nums[n - i];
}
for (auto i = 0; i < n; ++i) {
a[i] *= b[n - i - 1];
}
return a;
}```

• `a[n- 1]`不需要乘
• `a[n - 2] = a[n - 2] * nums[n - 1]`
• `a[n - 3] = a[n - 3] * nums[n - 1] * nums[n - 2]`
• ...
• `a[0] = a[0] * nums[n - 1] * nums[n - 2] * ... * nums[1]`

```vector<int> productExceptSelf(vector<int> &nums) {
if (nums.empty()) // 空
return vector<int>();
if (nums.size() == 1) { //只有一个元素，返回{0}
return vector<int>({0});
}
int n = nums.size();
vector<int> result(n, 1);
for (int i = 1; i < n; ++i)
result[i] = result[i - 1] * nums[i - 1];
int product = 1;
for (int i = n - 2; i >= 0; --i) {
product *= nums[i + 1];
result[i] *= product;
}
return result;

}```

You can’t perform that action at this time.