给定一个整数数组A。
定义B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], 计算B的时候请不要使用除法。
样例
给出A=[1, 2, 3],返回 B为[6, 3, 2]
Python:
class Solution:
"""
@param: nums: Given an integers array A
@return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
"""
def productExcludeItself(self, nums):
# write your code here
result = []
for i in range(len(nums)):
temp = 1
for j in range(len(nums)):
if j != i:
temp *= nums[j]
result.append(temp)
return result
C++:
class Solution {
public:
/*
* @param nums: Given an integers array A
* @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
*/
vector<long long> productExcludeItself(vector<int> &nums) {
// write your code here
vector<long long> result;
for (int i = 0; i < nums.size(); i++)
{
long long temp = 1;
for (int j = 0; j < nums.size(); j++)
{
if (i != j)
{
temp *= nums[j];
}
}
result.push_back(temp);
}
return result;
}
};