题解 | #牛群重量积#
牛群重量积
https://www.nowcoder.com/practice/d3c6930f140f4b7dbf3a53dd36742193
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型一维数组
*/
function productExceptSelf(nums) {
// write code here
let res = []
for (let i = 0; i < nums.length; i++) {
let item = null
if (i === 0) {
item = nums.slice(i + 2).reduce((a, b) => a * b)
} else if (i === nums.length - 1) {
item = nums.slice(0,i - 1).reduce((a, b) => a * b)
} else {
let left = 1
let right = 1
if (nums[i - 2]) {
let leftArr = nums.slice(0,i - 1)
left = leftArr.length > 0 ? leftArr.reduce((a, b) => a * b) : nums[i - 2]
}
if (nums[i + 2]) {
let rightArr = nums.slice(i + 2)
right = rightArr.length > 0 ? rightArr.reduce((a, b) => a * b) : nums[i + 2]
}
item = left * right
}
console.log("i", i, item)
res.push(item)
}
return res
}
module.exports = {
productExceptSelf: productExceptSelf
};

查看20道真题和解析