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.题目的意思要找出输入数组的“枢纽”点。这个“枢纽”的定义就是,这个元素全部左边的元素的加和恰好等于它全部右边元素的加和,而且咱们返回这个枢纽点的位置。若是不存在这样的“枢纽”,则返回-1.若是有多个这样的枢纽,则返回最左侧的枢纽点。数组
Example 1:
Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
nums[3]左边的元素和为11,恰好等于nums[3]右边的元素和。
Example 2:
Input:
nums = [1, 2, 3]
Output: -1
Explanation:
没有知足“枢纽”定义的元素。因此返回-1.this
public int pivotIndex(int[] nums) { int length = nums.length; if(length == 0 || length ==1)return -1; int sum = 0; for(int num : nums)sum += num; if(sum-nums[0] == 0)return 0; int left = 0; for(int i=1;i<length;i++){ left += nums[i-1]; if(sum - left - nums[i] == left){ return i; } } return -1; }