标签:center 代码 oid enter png img pre src length
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;
}
}
标签:center 代码 oid enter png img pre src length
原文地址:https://www.cnblogs.com/shimmernight/p/13530692.html