[LeetCode force buckle 724] Find the center index of the array. Given an integer type array nums, please write a method that can return the "center index" of the array.

learning target:

Goal: proficiently use the knowledge learned in Java


Subject content:

The content of this article: Implemented in Java: Finding the Center Index of an Array


Title description:

Given an array nums of integer type, write a method that returns the "center index" of the array.
We define the center index of the array like this: the sum of all elements on the left side of the center index of the array is equal to the sum of all elements on the right.
If the array does not have a central index, then we should return -1. If the array has multiple center indexes, then we should return the one closest to the left.

Example 1:

Input :
nums = [1, 7, 3, 6, 5, 6]
Output :
3
Explanation :
The sum (1 +7 + 3 = 11) of the left side of index 3 (nums[3] = 6), and the right The sum of the side numbers (5 + 6 = 11) is equal. At the same time, 3 is also the first center index that meets the requirements.

Example 2:

Input :
nums = [1, 2, 3]
Output :
-1
Explanation :
There is no center index that satisfies this condition in the array.

Problem-solving ideas:

We can use reverse thinking. If there is such an index, then the sum of the left value plus the sum of the right value plus the element at the index position is equal to the array sum, and the sum of the left value is equal to the sum of the right value;
so we You can traverse the array. If there is a position such that the sum of all values ​​on the left multiplied by 2 plus the current value is equal to the total sum of the array, then the position is the middle index;
Insert picture description here

Implementation code:

public class Practice_01 {
    
    
    public static void main(String[] args) {
    
    
        int[] nums = {
    
    1,2,3,4,3,2,1};
        System.out.println(pivotIndex(nums));
    }
    public static int pivotIndex(int[] nums) {
    
    
        int sum = 0;
        int leftSum = 0;//索引左侧元素和
        for (int i : nums) {
    
    
        //数组元素和
            sum += i;
        }
        for (int i = 0; i < nums.length; i++) {
    
    
            if (2 * leftSum + nums[i] == sum) {
    
    
                return i;
            } else {
    
    
                leftSum += nums[i];
            }
        }
        return -1;
    }
}

operation result:

3

Guess you like

Origin blog.csdn.net/zhangxxin/article/details/113093464