剑指offer 构建乘积数组
问题描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * … * A[n-1],B[n-1] = A[0] * A[1] * … * A[n-2];)
C++代码实现
思路:1.暴力破解,求哪位就不累乘哪位
2.求i
左边累乘,右边累乘,再相乘
class Solution {
public:
vector<int> multiply(const vector<int>& A) {
vector<int>B(A);
for (int i = 0; i < A.size(); i++)
{
int sum = 1;
for (int j = 0; j < A.size(); j++)
{
if (j != i)
{
sum *= A[j];
}
}
B[i] = sum;
}
return B;
}
};
class Solution {
public:
vector<int> multiply(const vector<int>& A) {
vector<int>B(A.size(), 1);
// B[i] => i前面的累乘(不包括i)
for (int i = 1; i < A.size(); i++)
{
B[i] = B[i-1] * A[i-1];
}
// temp表示右边累乘
int temp = 1;
for (int i = A.size() - 2; i >= 0; i--)
{
temp *= A[i+1];
B[i] *= temp;
}
return B;
}
};
python2代码实现
# -*- coding:utf-8 -*-
class Solution:
def multiply(self, A):
# write code here
B = [1] * len(A)
for i in range(1, len(A)):
B[i] = B[i-1] * A[i-1]
temp = 1
i = len(A) - 2
while i >= 0:
temp *= A[i+1]
B[i] *= temp
i -= 1
return B