- 题目描述
给定一个数组 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,3,4,5] 输出: [120,60,40,30,24]
- 解法
这道题题目的意思是B[I]为A中索引不为i的所有元素的乘积,看了好久题目,题目都看不懂。
然后解法的话,参考表格法,就一目了然了。既然不能使用除法,那么我就将下三角和上三角的对应行的位置元素相乘不就是B了嘛,这里需要注意一下索引。
class Solution: def constructArr(self, a: List[int]) -> List[int]: tmp = 1 b = [1] * len(a) for i in range(1, len(a)): b[i] = b[i-1] * a[i-1] for i in range(len(a)-2, -1, -1): tmp *= a[i+1] b[i] *= tmp return b
时间复杂度 O(N)O(N) : 其中 NN 为数组长度,两轮遍历数组 aa ,使用 O(N)O(N) 时间。
空间复杂度 O(1)O(1) : 变量 tmptmp 使用常数大小额外空间(数组 bb 作为返回值,不计入复杂度考虑)
参考链接:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/