Find the central index of the array


Given an array nums of integer type, write a method that returns the "center index" of the array. We define an array center index by saying that the sum of all elements to the left of the array center index is equal to the sum of all elements to the right. If the array does not have a central index, we should return -1. If the array has multiple central indexes, we should return the one nearest to the left.Copy the code

Example:


Input: nums = [1, 7, 3, 6, 5, 6] Output: 3 Description: The sum of left nums (1 + 7 + 3 = 11) is the same as the sum of right nums (5 + 6 = 11). Also, 3 is the first central index that meets the requirement. Input: nums = [1, 2, 3] Output: -1 Description: There is no central index in the array that meets this condition.Copy the code

Think about:


Let's iterate over the sum of all the elements in the array. The sum is then iterated over from the beginning. Each time the sum is twice the sum of the left elements plus the middle element. If the result is equal to sum, then the index is the central index.Copy the code

Implementation:


class Solution { public int pivotIndex(int[] nums) { int leftSum = 0, sum = 0; for (int num : nums) { sum = sum + num; } for (int count = 0; count <= nums.length - 1; count++) { if (count == 0) { leftSum = 0; } else { leftSum += nums[count - 1]; } if (leftSum * 2 + nums[count] == sum) { return count; } } return -1; }}Copy the code