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; }