Comments (1)
题解
两层循环可以解,但是复杂度不符合要求。
方法一:左右乘积列表
来自官方题解
var productExceptSelf = function(nums: number[]): number[] {
const length = nums.length;
// L 和 R 分别表示左右两侧的乘积列表
const L = new Array<number>(length);
const R = new Array<number>(length);
const answer = new Array<number>(length);
// L[i] 为索引 i 左侧所有元素的乘积
// 对于索引为 '0' 的元素,因为左侧没有元素,所以 L[0] = 1
L[0] = 1;
for (let i = 1; i < length; i++) {
L[i] = nums[i - 1] * L[i - 1];
}
// R[i] 为索引 i 右侧所有元素的乘积
// 对于索引为 'length-1' 的元素,因为右侧没有元素,所以 R[length-1] = 1
R[length - 1] = 1;
for (let i = length - 2; i >= 0; i--) {
R[i] = nums[i + 1] * R[i + 1];
}
// 对于索引 i,除 nums[i] 之外其余各元素的乘积就是左侧所有元素的乘积乘以右侧所有元素的乘积
for (let i = 0; i < length; i++) {
answer[i] = L[i] * R[i];
}
return answer;
};
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
const ret = [];
for (let i = 0, temp = 1; i < nums.length; i++) {
ret[i] = temp;
temp *= nums[i];
}
for (let i = nums.length - 1, temp = 1; i >= 0; i--) {
ret[i] *= temp;
temp *= nums[i];
}
return ret;
};
from leetcode.
Related Issues (20)
- 217.存在重复元素 HOT 1
- 4.寻找两个正序数组的中位数 HOT 1
- 8.字符串转换整数 (atoi) HOT 1
- 237.删除链表中的节点 HOT 1
- 46.全排列 HOT 1
- 160.相交链表 HOT 1
- 61.旋转链表 HOT 1
- 2.两数相加 HOT 1
- 21.合并两个有序链表 HOT 1
- 92.反转链表 II HOT 1
- 206. 反转链表 HOT 1
- 146. LRU 缓存机制 HOT 1
- 94. 二叉树的中序遍历 HOT 1
- 235. 二叉搜索树的最近公共祖先 HOT 1
- 236. 二叉树的最近公共祖先 HOT 1
- 104. 二叉树的最大深度 HOT 1
- 111. 二叉树的最小深度 HOT 1
- 543. 二叉树的直径 HOT 1
- 124.二叉树中的最大路径和 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from leetcode.