文章作者:Tyan
部落格:noahsnail.com | CSDN | 簡書
1. Description
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAjM2EzLcd3LcJzLcJzdllmVldWYtl2Pn5GcuYWNiN2MxQTNhNTZxUGOiRTZlZWOmZTOykzYkJjYxQDMvw1M4YDNyETMtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
2. Solution
**解析:**Version 1,先将數組分為左右兩邊,左邊為
,右邊是數組總和,周遊數組,左邊加上目前位置的前一個數,右邊減去目前位置的數,如果左右相等,傳回目前索引,這樣優先找到的是滿足條件的最左邊的索引,最後沒找到,傳回
-1
。
- Version 1
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left = 0
right = sum(nums)
for i in range(len(nums)):
if i > 0:
left += nums[i-1]
right -= nums[i]
if left == right:
return i
return -1
複制
Reference
- https://leetcode.com/problems/find-pivot-index/