[LeetCode] 724. Find Pivot Index

 

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 <= 104
  • -1000 <= nums[i] <= 1000

寻找数组的中心下标。

给你一个整数数组 nums ,请计算数组的 中心下标 。

数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。

如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-pivot-index
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是给一个数组,找到一个中心索引。这个中心索引 i 的定义是使得数组在 i 左边的子数组的和 = 数组在 i 右边的子数组的和,其中左右两边的计算不包括 nums[i]。

思路是前缀和。我们先计算整个数组的前缀和 sum。再次扫描数组,此时我们需要再找一个左起的前缀和 leftSum ,同时找一个 index 满足 leftSum = sum - nums[i] - leftSum。如果能找到就返回这个 index,如果找不到就返回 -1。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int pivotIndex(int[] nums) {
 3         int sum = 0;
 4         for (int num : nums) {
 5             sum += num;
 6         }
 7 
 8         int leftSum = 0;
 9         for (int i = 0; i < nums.length; i++) {
10             if (leftSum == sum - nums[i] - leftSum) {
11                 return i;
12             }
13             leftSum += nums[i];
14         }
15         return -1;
16     }
17 }

 

LeetCode 题目总结

posted @ 2020-10-30 10:15  CNoodle  阅读(140)  评论(0编辑  收藏  举报