跳至主要內容

724. Find Pivot Index


724. Find Pivot Indexopen in new window

🟢   🔖  数组 前缀和  🔗 LeetCodeopen in new window

题目

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example 1:

Input: nums = [1,7,3,6,5,6]

Output: 3

Explanation:

The pivot index is 3.

Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11

Right sum = nums[4] + nums[5] = 5 + 6 = 11

Example 2:

Input: nums = [1,2,3]

Output: -1

Explanation:

There is no index that satisfies the conditions in the problem statement.

Example 3:

Input: nums = [2,1,-1]

Output: 0

Explanation:

The pivot index is 0.

Left sum = 0 (no elements to the left of index 0)

Right sum = nums[1] + nums[2] = 1 + -1 = 0

Constraints:

  • 1 <= nums.length <= 10^4
  • -1000 <= nums[i] <= 1000

Note: This question is the same as 1991

题目大意

给定一个整数类型的数组  nums,请编写一个能够返回数组 “中心索引” 的方法。我们是这样定义数组 中心索引 的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。

解题思路

  • 在数组中,找到一个数,使得它左边的数之和等于它的右边的数之和,如果存在,则返回这个数的下标索引,否作返回 -1。
  • 这里面存在一个等式,只需要满足这个等式即可满足条件:leftSum + num[i] = sum - leftSum => 2 * leftSum + num[i] = sum
  • 题目提到如果存在多个索引,则返回最左边那个,因此从左开始求和,而不是从右边。

代码

// 2 * leftSum + num[i] = sum
// 时间: O(n)
// 空间: O(1)
/**
 * @param {number[]} nums
 * @return {number}
 */
var pivotIndex = function (nums) {
	const total = nums.reduce((a, b) => a + b, 0);
	let leftSum = 0;
	for (let i = 0; i < nums.length; i++) {
		if (2 * leftSum + nums[i] === total) {
			return i;
		}
		leftSum += nums[i];
	}
	return -1;
};

相关题目

相关题目
- [560. 和为 K 的子数组](https://leetcode.com/problems/subarray-sum-equals-k)
- [1991. 找到数组的中间位置](https://leetcode.com/problems/find-the-middle-index-in-array)
- [2270. 分割数组的方案数](https://leetcode.com/problems/number-of-ways-to-split-array)
- [🔒 Maximum Sum Score of Array](https://leetcode.com/problems/maximum-sum-score-of-array)
- [2574. 左右元素和的差值](https://leetcode.com/problems/left-and-right-sum-differences)