search
HomeJavaJavagetting StartedHow to find the center index of an array in java

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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment