题目:LCR 012
解法一:前缀和
前缀和在遍历时叠加,后缀和=数组元素总和 - 当前遍历元素 - 当前元素前缀和
class Solution {
public int pivotIndex(int[] nums) {
int res = -1;
int prefixSum = 0;
int suffixSum = Arrays.stream(nums).sum();
for (int i = 0; i < nums.length; i++) {
suffixSum -= nums[i];
if (suffixSum == prefixSum) return i;
prefixSum += nums[i];
}
return res;
}
}