今天我们来做一道LeetCode上的题目,原题链接:剑指 Offer 66. 构建乘积数组
题目描述
- 给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 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]
- 提示:
所有元素乘积之和不会溢出 32 位整数
a.length <= 100000
思路分析
- B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]
- 转换公式:B[i]=A[0]×A[1]×…×A[i-1]× 1 × A[i+1]×…×A[n-1]
- 理解公式:
- 初始化:数组 B,其中 B[i] = 0;
- 计算 B 的下三角各元素的乘积,记为result_1;
- 计算 B 的上三角各元素的乘积,记为result_2;
- 计算上、下三角各元素乘积,result_1[i] * result_2[i] = result_3
- 返回 result_3
- 示例表示
1 2 3 4 5
下三角乘积 ----->
1 1 2 6 24
上三角乘积 ----->
120 60 20 5 1
最终乘积 ----->
120 60 40 30 24
代码
# Python
class Solution(object):
def constructArr(self, a):
"""
:type a: List[int]
:rtype: List[int]
"""
# V1 版本
# result_1 = [1] * len(a)
# result_2 = [1] * len(a)
# a_size = len(a)
# for i in range(1, a_size):
# result_1[i] = result_1[i - 1] * a[i - 1]
# for i in range(a_size - 1):
# result_2[a_size - i - 2] = result_2[a_size - i - 1] * a[a_size - i - 1]
# return [result_1[i] * result_2[i] for i in range(a_size)]
# V2 版本
# result_1 = [1] * len(a)
# result_2 = [1] * len(a)
# a_size = len(a)
# for i in range(1, a_size):
# result_1[i] = result_1[i-1] * a[i - 1]
# for i in range(a_size - 2, -1, -1):
# result_2[i] = result_2[i + 1] * a[i + 1]
# return [result_1[i] * result_2[i] for i in range(a_size)]
# V3 版本
result = [1] * len(a)
a_size = len(a)
for i in range(1, a_size):
result[i] = result[i-1] * a[i - 1]
temp = 1
for i in range(a_size - 2, -1, -1):
temp *= a[i + 1]
result[i] *= temp
return result
总结
- V1 版本简单实现
- V2 版本:使用
range(a_size - 2, -1, -1)创建数组,eg:[4, 3, 2, 1, 0] - V3 版本:基于V2版本,优化了内存占用
参考
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情