题目描述:

代码:
class Solution:
def pivotIndex(self, nums):
if len(nums) == 0:
return -1
if sum(nums[1:])==0:
return 0
total = sum(nums)
now = nums[0]*2;
for i in range(1, len(nums)-1):
if now + nums[i] == total:
return i
now+=nums[i]*2
if sum(nums[0:len(nums)-1])==0:
return len(nums)-1
return -1;
测试代码:
from solution import *
nums = [1, 7, 3, 6, 5, 6]
print(Solution().pivotIndex(nums))
运行结果:

本文介绍了一种寻找数组中心索引的方法,通过计算数组元素的总和与当前元素的两倍值来确定中心索引的位置。该算法适用于任何整数类型的数组,并提供了完整的Python实现代码。
966

被折叠的 条评论
为什么被折叠?



