The center index means that the sum of all the values on the left of the center index is equal to the sum of all the values on the right of the center index. If there is no such index, it returns -1.
E.g:
Target array: [1,2,3,5,6]
Output: 3 (this means that the index is not a value, that is, num[3])
Explanation: The value of 5 on the left is added to 6 to equal the value of 6 on the right.
C language problem solution
/*
@nums:数组
@numsSize:数组长度
*/
int pivotIndex(int* nums,int numsSize){
int sum=0,i=0,left=0;
// 计算出数组的总和
for(i=0;i<numsSize;i++){
sum+=nums[i];
};
//寻找中心索引
for(i=0;i<numsSize;i++){
//若左边和右边的和相同
if(left == sum - nums[i] - left){
return i;
}
//否则就加入left
left += nums[i];
};
//无返回值,说明无中心索引
return -1;
}