题目描述:
给你一个整数数组 nums ,请计算数组的 中心下标 。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
解题思路:
假设数组中心下标存在,则左边和为sum,右边和为 total-sum-nums[i],左右相等,成立等式,即2*sum + nums[i] == total
package com.hh.level1.day1;
import java.util.Arrays;
public class PivotIndex {
public int pivotIndex(int[] nums) {
/*int total = 0;
for (int i = 1; i <= nums.length; i++) {
total = total + nums[i - 1];
}*/
int total = Arrays.stream(nums).sum();//求整个数组的和
int sum = 0;
for (int i = 0; i < nums.length; i++) {
//假设数组中心下标存在,则左边和为sum,右边和为 total-sum-nums[i],左右相等,成立等式
//即2*sum + nums[i] == total
if (2*sum + nums[i] == total){
return i;
}
sum += nums[i];
}
return -1;
}
public static void main(String[] args) {
PivotIndex pi = new PivotIndex();
int[] nums = {1, 7, 3, 6, 5, 6};
int total = pi.pivotIndex(nums);
System.out.println(total);
}
/*
*扩展知识
// 整数数组求和
int[] nums = {1,2,3,4,5};
int sum = Arrays.stream(nums).sum();
// List求和
int sum = list.stream().mapToInt(Integer::intValue).sum();
*/
}