LeetCode-724. Find Pivot Index-Analysis and Code (Java)

LeetCode-724. Find the center index of the array [Find Pivot Index]-analysis and code [Java]

1. Topic

Given you an integer array nums, please write a method that returns the "center index" of the array.
The center index of the array is an index of the array, and the sum of all elements on the left is equal to the sum of all elements on the right.
If the center index does not exist in the array, -1 is returned. If the array has multiple center indexes, the one closest to the left should be returned.
Note: The center index may appear at both ends of the array.

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
解释:
数组中不存在满足此条件的中心索引。

Example 3:

输入:nums = [2, 1, -1]
输出:0
解释:
索引 0 左侧不存在元素,视作和为 0 ;右侧数之和为 1 + (-1) = 0 ,二者相等。

Example 4:

输入:nums = [0, 0, 0, 0, 1]
输出:4
解释:
索引 4 左侧数之和为 0 ;右侧不存在元素,视作和为 0 ,二者相等。

prompt:

  • The length range of nums is [0, 10000].
  • Any nums[i] will be an integer in the range [-1000, 1000].

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/find-pivot-index The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Direct accumulation

(1) Thinking

Design two integers to record the sum of the left and right elements of the current index respectively, until the center index is found or the traversal is completed.

(2) Code

class Solution {
    
    
    public int pivotIndex(int[] nums) {
    
    
        if (nums.length == 0)
            return -1;
        int left = 0, right = 0;//左、右侧元素累加值
        for (int i = 1; i < nums.length; i++)//计算右侧元素累加值
            right += nums[i];
        for (int i = 0; i < nums.length - 1; i++) {
    
    
            if (left == right)
                return i;
            left += nums[i];
            right -= nums[i + 1];
        }
        if (left == right)//确定最后一个索引是否符合
            return nums.length - 1;
        return -1;
    }
}

(3) Results

Execution time: 1 ms, beating 100.00% of users
in all Java submissions ; memory consumption: 39.2 MB, beating 49.72% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/113785751