版权声明:本文为博主原创文章,请尊重原创,转载请注明原文地址和作者信息! https://blog.csdn.net/zzc15806/article/details/82384523
class Solution:
# 基本想法,遍历数组,但是 Time Limit Exceeded
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return -1
for i in range(len(nums)):
if sum(nums[:i]) == sum(nums[i+1:]):
return i
return -1
class Solution:
# 只计算数组和的一半,节省计算资源
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
size = sum(nums)
left = 0
for i in range(len(nums)):
if left * 2 + nums[i] == size:
return i
left += nums[i]
return -1