Description
- 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 the numbers to the left of the index is equal to the sum of 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.
寻找数组“中心索引”:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和
Solution
- 转换思路,联系整个数组;
- 左右两边和相等,即原数组的和 = 左边和 * 2 + 中心元素;
class Solution {
public int pivotIndex(int[] nums) {
int total = 0, sum = 0;
for (int num : nums) total += num; //先计算出数组总和
for (int i = 0; i < nums.length; sum += nums[i++])
if (sum * 2 == total - nums[i]) return i;
return -1;
}
}
解法参考:
https://leetcode.com/problems/find-pivot-index/discuss/109274/JavaC%2B%2B-Clean-Code
网友评论