Skip to content

Commit b945211

Browse files
committed
238. 除自身以外数组的乘积
1 parent 1b9cc9d commit b945211

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@
113113
|235|[二叉搜索树的最近公共祖先](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/)|[JavaScript](./algorithms/lowest-common-ancestor-of-a-binary-search-tree.js)|Easy|
114114
|236|[二叉树的最近公共祖先](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/)|[JavaScript](./algorithms/lowest-common-ancestor-of-a-binary-tree.js)|Medium|
115115
|237|[删除链表中的节点](https://leetcode-cn.com/problems/delete-node-in-a-linked-list/)|[JavaScript](./algorithms/delete-node-in-a-linked-list.js)|Easy|
116+
|238|[除自身以外数组的乘积](https://leetcode.cn/problems/product-of-array-except-self/)|[JavaScript](./algorithms/product-of-array-except-self.js)|Medium|
116117
|239|[滑动窗口最大值](https://leetcode.cn/problems/sliding-window-maximum/)|[JavaScript](./algorithms/sliding-window-maximum.js)|Hard|
117118
|242|[有效的字母异位词](https://leetcode.cn/problems/valid-anagram/)|[JavaScript](./algorithms/valid-anagram.js)|Easy|
118119
|257|[二叉树的所有路径](https://leetcode.cn/problems/binary-tree-paths/)|[JavaScript](./algorithms/binary-tree-paths.js)|Easy|
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* 238. 除自身以外数组的乘积
3+
* @param {number[]} nums
4+
* @return {number[]}
5+
*/
6+
var productExceptSelf = function (nums) {
7+
let result = Array(nums.length).fill(1);
8+
let left = 1; // 从左边累乘
9+
let right = 1; // 从右边累乘
10+
let n = nums.length;
11+
12+
for (let i = 0; i < nums.length; i++) {
13+
result[i] *= left; // 乘以其左边的乘积
14+
left *= nums[i];
15+
16+
result[n - 1 - i] *= right; // 乘以其右边的乘积
17+
right *= nums[n - 1 - i];
18+
}
19+
20+
return result;
21+
};

0 commit comments

Comments
 (0)