题目描述
思路
代码实现
package com.zxl.数组.查找索引;
public class Demo03 {
public static void main(String[] args) {
int[] arrays = new int[]{1, 7, 3, 6, 5};
int center = getCenterIndex(arrays);
System.out.println(center);
}
// 获取中心索引
public static int getCenterIndex(int[] nums) {
int sum = 0;
for (int array : nums) {
sum += array;
}
for (int i = 0; i <= nums.length - 1; i++) {
int sumLeft = 0;
int sumRight = 0;
for (int j = i - 1;j >= 0; j--) {
sumLeft += nums[j];
}
sumRight = sum - sumLeft - nums[i];
if (sumLeft == sumRight) {
return i;
}
}
return -1;
}
}