add: 除自身以外数组的乘积
This commit is contained in:
parent
4aa8eba735
commit
8da050ef53
@ -366,6 +366,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
|
||||
- LeetCode 1431. 拥有最多糖果的孩子 <https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies/>
|
||||
|
||||
- [除自身以外数组的乘积](src/array/product-of-array-except-self.js)
|
||||
|
||||
- LeetCode 238. 除自身以外数组的乘积 <https://leetcode-cn.com/problems/product-of-array-except-self/>
|
||||
|
||||
## 栈
|
||||
|
||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||
|
21
src/array/product-of-array-except-self.js
Normal file
21
src/array/product-of-array-except-self.js
Normal file
@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number[]}
|
||||
*/
|
||||
export const productExceptSelf = function (nums) {
|
||||
const ans = []
|
||||
for (let i = 0, len = nums.length; i < len; i++) {
|
||||
let tmpL = 1
|
||||
let tmpR = 1
|
||||
for (let j = 0; j < len; j++) {
|
||||
if (j < i) {
|
||||
tmpL *= nums[j]
|
||||
} else if (j > i) {
|
||||
tmpR *= nums[j]
|
||||
}
|
||||
}
|
||||
ans.push(tmpL * tmpR)
|
||||
}
|
||||
|
||||
return ans
|
||||
}
|
5
test/array/product-of-array-except-self.test.js
Normal file
5
test/array/product-of-array-except-self.test.js
Normal file
@ -0,0 +1,5 @@
|
||||
import { productExceptSelf } from '../../src/array/product-of-array-except-self'
|
||||
|
||||
test('除自身以外数组的乘积', () => {
|
||||
expect(productExceptSelf([1, 2, 3, 4])).toEqual([24, 12, 8, 6])
|
||||
})
|
Loading…
Reference in New Issue
Block a user