Home >Java >Javagetting Started >How to find the center index of an array in java
Purpose:
Given an array nums of integer type, please write a method that returns the "center index" of the array.
Array center index definition:
The sum of all the elements on the left side of the array center index is equal to the sum of all the elements on the right side of the array center index. If the array does not have a center index, then we should return -1. If the array has multiple center indices, then we should return the one closest to the left.
Related video tutorial recommendations: java video
Example 1:
输入: nums = [1, 7, 3, 6, 5, 6] 输出: 3 解释: 索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。 同时, 3 也是第一个符合要求的中心索引。
Example 2:
输入: nums = [1, 2, 3] 输出: -1 解释: 数组中不存在满足此条件的中心索引。
Instructions:
The length range of nums is [0, 10000].
Any nums[i] will be an integer in the range [-1000, 1000].
Solution idea:
Use sum, leftSum, and rightSum to store the sum respectively, the sum on the left side of i, and the sum on the right side of i. Calculate a total sum first for the convenience of the following calculations, and then move one i from left to right, note that i needs to be considered separately when it is the first element. Calculate the values on the left and right of i respectively and compare them. If leftSum=rightSum, return i.
java code:
class Solution { public int pivotIndex(int[] nums) { if (nums == null || nums.length == 0) { return -1; } int sum = 0; int leftSum = 0; int rightSum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; } for (int i = 0; i < nums.length; i++) { if (i == 0) { leftSum = 0; } else { leftSum += nums[i - 1]; } rightSum = sum - leftSum - nums[i]; if (leftSum == rightSum) { return i; } } return -1; } }
Recommended tutorial: Getting started with java
The above is the detailed content of How to find the center index of an array in java. For more information, please follow other related articles on the PHP Chinese website!