数组-寻找数组的中心索引
2021-04-01 15:25
标签:center 代码 oid enter png img pre src length 数组-寻找数组的中心索引 标签:center 代码 oid enter png img pre src length 原文地址:https://www.cnblogs.com/shimmernight/p/13530692.html题目描述
思路
代码实现
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 = 0; j--) {
sumLeft += nums[j];
}
sumRight = sum - sumLeft - nums[i];
if (sumLeft == sumRight) {
return i;
}
}
return -1;
}
}