We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
面试题66. 构建乘积数组
给定一个数组 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]
提示:
所有元素乘积之和不会溢出 32 位整数 a.length <= 100000
B[i]的意义是A数组不包括i位置的所有乘积,分为i左边的元素乘积和i右边的所有的元素乘积。
B[i]
A
i
对称遍历
/** * @param {number[]} a * @return {number[]} */ var constructArr = function(a) { const len = a.length; let B = []; if(len > 0) { // 第一个 for 计算左边的乘积 // 初始化 B[0] = 1, 是因为0左边没有元素, 所以乘积为1 B[0] = 1; for(let i = 1; i < len; i++) { B[i] = B[i - 1] * a[i - 1]; } // 第二个for计算右边的 let right = 1; for(let i = len - 2; i>= 0; i--) { right *= a[i + 1]; B[i] *= right; } } return B; };
复杂度为O(n),没有嵌套的for, 而是顺序的for;
The text was updated successfully, but these errors were encountered:
No branches or pull requests
面试题66. 构建乘积数组
题目描述
给定一个数组 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]。不能使用除法。
示例:
提示:
所有元素乘积之和不会溢出 32 位整数
a.length <= 100000
思路分析
B[i]
的意义是A
数组不包括i
位置的所有乘积,分为i
左边的元素乘积和i
右边的所有的元素乘积。对称遍历
解题方法
复杂度为O(n),没有嵌套的for, 而是顺序的for;
The text was updated successfully, but these errors were encountered: