题目
代码
function findCenterIndex(nums) {
// 当数组只有一个元素时,该元素即为中心位置
if (nums.length === 1) {
return 0;
}
// 初始化左侧乘积和右侧乘积
let leftProduct = 1;
let totalProduct = nums.reduce((acc, num) => acc * num, 1);
for (let i = 0; i < nums.length; i++) {
// 更新右侧乘积
totalProduct /= nums[i];
// 如果左侧和右侧乘积相等,返回当前索引作为中心位置
if (leftProduct === totalProduct) {
return i;
}
// 更新左侧乘积
leftProduct *= nums[i];
}
// 如果没有找到中心位置,返回-1
return -1;
}
let numbers = [2, 5, 3, 6, 5, 6];
console.log(findCenterIndex(numbers)); // 输出:3