构建乘积数组(数组)
来源:互联网 发布:孕期食谱软件 编辑:程序博客网 时间:2024/06/03 21:09
题目描述:给定一个数组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[i]的值可以看作矩阵中每行的乘积。
先计算下三角中的连乘,即我们先算出B[i]中的一部分,然后倒过来按上三角中的分布规律,把另一部分也乘进去。
import java.util.ArrayList;public class Solution { public int[] multiply(int[] A) { int[] B = new int[A.length]; B[0] = 1; for (int i = 1; i < A.length; i++) B[i] = B[i - 1] * A[i - 1]; int tmp = 1; for (int i = A.length - 2; i >= 0; i--) { tmp *= A[i + 1]; B[i] *= tmp; } return B; }}
思路二:
B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]
从左到右算 B[i]=A[0]*A[1]*...*A[i-1]
从右到左算B[i]*=A[i+1]*...*A[n-1]
import java.util.ArrayList;public class Solution { public int[] multiply(int[] A) { int[] B = new int[A.length]; int res = 1; for (int i = 0; i < A.length; res *= A[i++]) B[i] = res; res = 1; for (int i = A.length - 1; i >= 0; res *= A[i--]) B[i] *= res; return B; }}
阅读全文
0 0
- 构建乘积数组(数组)
- 数组------构建乘积数组
- 数组:构建乘积数组
- 构建乘积数组
- 构建乘积数组
- 52 - 构建乘积数组
- 构建乘积数组
- 构建乘积数组
- 构建乘积数组
- 牛客网 | 构建乘积数组
- 构建乘积数组
- 【模模糊糊】构建乘积数组
- 构建乘积数组
- 构建乘积数组
- 构建乘积数组
- 构建乘积数组
- 构建乘积数组
- 构建乘积数组
- nginx安装,端口配置
- 【Linux】VMware虚拟机中如何配置静态IP
- Android 永久隐藏导航栏,系统栏的方法
- 金海佳学C++primer 练习9.20
- js with语句
- 构建乘积数组(数组)
- QT工具栏的制作
- 微信小程序-wx.request获取数据
- mysql5.7开启慢查询日志
- 第十二周-项目1-验证算法-Dijkstra算法
- 常用的一些sql语句查询
- 第十四周项目3---是否二叉排序树?
- Life Cycle of a Linux Program
- webstorm缺点