LeetCode724-寻找数组的中心索引

题目链接

英文链接:https://leetcode.com/problems/find-pivot-index/

中文链接:https://leetcode-cn.com/problems/find-pivot-index/

题目详述

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

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

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

示例 1:

1
2
3
4
5
6
输入: 
nums = [1, 7, 3, 6, 5, 6]
输出: 3
解释:
索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。
同时, 3 也是第一个符合要求的中心索引。

示例 2:

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

说明:

  • nums 的长度范围为 [0, 10000]。
  • 任何一个 nums[i] 将会是一个范围在 [-1000, 1000]的整数。

题目详解

  • 类似于 LeetCode560-和为K的子数组LeetCode525-连续数组,本题也可以采用求前缀和的方式来解答。
  • 先求得数组所有元素之和。
  • 遍历数组,求前缀和,这样当前元素左侧和右侧元素之和很容易得到。如果满足条件,直接返回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class LeetCode_00724 {

public int pivotIndex(int[] nums) {
int sum = Arrays.stream(nums).sum();
int s = 0;
for (int i = 0; i < nums.length; ++i) {
if (s << 1 == sum - nums[i]) {
return i;
}
s += nums[i];
}
return -1;
}
}