forked from azl397985856/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path238.product-of-array-except-self.js
56 lines (52 loc) · 1.46 KB
/
238.product-of-array-except-self.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* @lc app=leetcode id=238 lang=javascript
*
* [238] Product of Array Except Self
*
* https://leetcode.com/problems/product-of-array-except-self/description/
*
* algorithms
* Medium (53.97%)
* Total Accepted: 246.5K
* Total Submissions: 451.4K
* Testcase Example: '[1,2,3,4]'
*
* Given an array nums of n integers where n > 1, return an array output such
* that output[i] is equal to the product of all the elements of nums except
* nums[i].
*
* Example:
*
*
* Input: [1,2,3,4]
* Output: [24,12,8,6]
*
*
* Note: Please solve it without division and in O(n).
*
* Follow up:
* Could you solve it with constant space complexity? (The output array does
* not count as extra space for the purpose of space complexity analysis.)
*
*/
/**
* @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];
}
// 此时ret[i]存放的是前i个元素相乘的结果(不包含第i个)
// 如果没有上面的循环的话,
// ret经过下面的循环会变成ret[i]存放的是后i个元素相乘的结果(不包含第i个)
// 我们的目标是ret[i]存放的所有数字相乘的结果(不包含第i个)
// 因此我们只需要对于上述的循环产生的ret[i]基础上运算即可
for (let i = nums.length - 1, temp = 1; i >= 0; i--) {
ret[i] *= temp;
temp *= nums[i];
}
return ret;
};