构建乘积数组
题目
给定一个数组 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]。不能使用除法。
思路1 对称遍历
思路2 表格分区
C++ 对称遍历,左右相乘
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
int n=a.size();
vector<int> res(n, 1);
int left = 1;
for(int i=0;i<n;++i)
{
res[i]=left;
left *= a[i];
}
int right = 1;
for(int i=n-1;i>=0;--i)
{
res[i] *= right;
right *= a[i];
}
return res;
}
};
python
class Solution:
def constructArr(self, a: List[int]) -> List[int]:
b, temp = [1]*len(a), 1
for i in range(1, len(a)):
b[i]=b[i-1]*a[i-1] # 下三角
for i in range(len(a)-2, -1, -1):
temp *= a[i+1]
b[i] *= temp
return b
python 直接构建表格,超时
class Solution:
def constructArr(self, a: List[int]) -> List[int]:
matrix = []
for i in range(len(a)):
row = []
for j in range(len(a)):
if j==i:
row.append(1)
else:
row.append(a[j])
matrix.append(row)
b = []
for i in range(len(matrix)):
temp = 1
for j in range(len(matrix[0])):
temp *= matrix[i][j]
b.append(temp)
return b