# 238. Product of Array Except Self 除自身以外数组的乘积

@TOC

## # 题目描述

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].
``````

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(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
_len = len(nums)
prod = 1
for i in range(_len):
prod *= nums[i]
prod = 1
for i in range(_len - 1, -1, -1):
prod *= nums[i]
``````

C++代码如下：

``````class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
const int N = nums.size();
vector<int> res(N, 1);
int prod = 1;
for (int i = 0; i < N; i ++) {
res[i] = prod;
prod *= nums[i];
}
prod = 1;
for (int i = N - 1; i >= 0; i--) {
res[i] *= prod;
prod *= nums[i];
}
return res;
}
};
``````

## # 日期

2018 年 2 月 14 日 2018 年 12 月 14 日 —— 12月过半，2019就要开始