# leetcode解題:(Easy) 724. Find Pivot Index
題目:[https://leetcode.com/problems/find-pivot-index/description/](https://leetcode.com/problems/find-pivot-index/description/)
描述:給定一個陣列,找出該陣列中最小的pivot index,找不到則回傳-1。pivot index的定義為,如果陣列第i個元素以左的元素總和及以右的元素總和(皆不包含第i個元素)相等則i即為該陣列的pivot index
解題思路:首先先計算陣列全部元素的總和,接著只要將原先是全部元素總和的右邊總和持續減去第i號元素,左邊總和持續加上第i號元素就能在O(n)時間內比較所有index的左右總和
程式碼:
```JAVA=
class Solution {
public int pivotIndex(int[] nums) {
int left = 0, right = 0;
for(int num : nums) right += num;
for(int i = 0; i < nums.length; i++) {
right -= nums[i];
if(left == right) return i;
left += nums[i];
}
return -1;
}
}
```
時間複雜度:O(n)
空間複雜度:O(1)
註:在leetcode上還有一題跟這題解法完全一樣:[1991. Find the Middle Index in Array](https://leetcode.com/problems/find-the-middle-index-in-array/)
###### tags: `leetcode` `easy`