题目

leetcode 724 寻找数组的中心索引

给定一个整数类型的数组 nums,请编写一个能够返回数组 “中心索引” 的方法。

我们是这样定义数组 中心索引 的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。

如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/find-pivot-index

代码

  1. class Solution {
  2. public int pivotIndex(int[] nums) {
  3. int sum=0;
  4. for (int i = 0; i < nums.length; i++) {
  5. sum+=nums[i];
  6. }
  7. int temp=0;
  8. for (int i = 0; i < nums.length; i++) {
  9. if(temp==sum-temp-nums[i])return i;
  10. temp+=nums[i];
  11. }
  12. //数组左边和*2+i=总和
  13. return -1;
  14. }
  15. }