【LeetCode】724. Find Pivot Index 寻找数组的中心索引(Easy)(JAVA)每日一题

【LeetCode】724. Find Pivot Index 寻找数组的中心索引(Easy)(JAVA)

题目地址: https://leetcode.com/problems/find-pivot-index/

题目描述:

Given an array of integers nums, write a method that returns the “pivot” index of this array.

We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:

Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.

Constraints:

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

题目大意

给定一个整数类型的数组 nums,请编写一个能够返回数组 “中心索引” 的方法。

我们是这样定义数组 中心索引 的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。

如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。

解题方法

  1. 先遍历一遍求出数组的总和
  2. 再次遍历,因为“中心索引”会把数组分成两份,而且左右两边和是一样的,所以 pre * 2 + nums[i] == sum 的位置就是 “中心索引”
  3. 时间复杂度 O(n)
class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        int pre = 0;
        for (int i = 0; i < nums.length; i++) {
            if (pre * 2 + nums[i] == sum) return i;
            pre += nums[i];
        }
        return -1;
    }
}

执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:39.2 MB,击败了40.28% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/113307420