题目:给定一个整数数组nums,请编写一个返回‘中心下标’的方法
中心下标是数组的一个下标,其左侧所有的元素相加的和,等于右侧所有元素相加的和。不存在则返回 -1,多个则返回靠近左侧的下标。
思路: 先统计出整个数组的总和,然后从第一个元素开始叠加,若当前叠加数不等于总和,则总和递减当前元素,随后继续循环,直到两个值相等。
public class ArrayCenterIndex {
public static void main(String[] args) {
System.out.println(pivotIndex(new int[]{1, 7, 3, 6, 0, 5, 6}));
}
public static int pivotIndex(int[] nums) {
int sum = Arrays.stream(nums).sum();
int total = 0;
for (int i = 0; i < nums.length; i++) {
total += nums[i];
if (total == sum) {
return i;
}
sum = sum - nums[i];
}
return -1;
}
}