Home > Java > Javagetting Started > How to find the center index of an array in java

How to find the center index of an array in java

王林
Release: 2020-04-20 16:09:59
forward
2453 people have browsed it

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 也是第一个符合要求的中心索引。
Copy after login

Example 2:

输入: 
nums = [1, 2, 3]
输出: -1
解释: 
数组中不存在满足此条件的中心索引。
Copy after login

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;
    }
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template