- LeetCode 238. Product of Array E
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
除自身以外数组元素的乘积。先求出整个数组的乘积,再除以当前元素,需要考虑0的个数。或将某个位置上的元素的乘积,等于左边的元素积乘以右边元素的乘积。
- Runtime: 120 ms, faster than 70.15%
- Memory Usage: 48.9 MB, less than 77.30%
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
let len = nums.length
if(len === 0) return []
let triple = 1
let zero = 0
for(let i = 0; i < len; i++) {
if(nums[i]) {
triple *= nums[i]
} else {
zero++
}
}
let res = Array(len).fill(0)
if(zero === 1) {
let index = nums.indexOf(0)
res[index] = triple
} else if(zero === 0) {
for(let i = 0; i < len; i++) {
res[i] = triple / nums[i]
}
}
return res
};
网友评论