Leetcode - 724 Find Pivot Index (Easy)
题目描述:以中枢点为界,左右两边元素之和相等。
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.
public int pivotIndex(int[] nums) {
int sum = 0, leftSum = 0;
for (int num : nums) {
sum += num;
}
for (int i = 0; i < nums.length; i++) {
if (leftSum == sum - leftSum - nums[i]) return i;
leftSum += nums[i];
}
return -1;
}