数组中某一个下标,左右两边的元素之和相等,该下标即为中心索引
public static void main(String[] args) {
int index=midIndex(new int[]{1,7,3,6,5,6});
System.out.println(index);
}
static int sum(int []arr){
int sum=0;
for (int i = 0; i < arr.length; i++) {
sum+=arr[i];
}
return sum;
}
public static int midIndex(int[]arr){
int sum1=0;
int sum= sum(arr);
// System.out.println(sum);
for (int i = 0; i < arr.length; i++) {
sum1+=arr[i];
if (sum==sum1){
return i;
}
sum=sum-arr[i];
}
return -1;
}