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.
求一个数组中左边之和等于右边之和的数的索引值
本来想直接循环加sum(nums[:i])
但是时间复杂度太大,测试只能过40%,然后改啊改
class Solution:
"""
@param nums: an array
@return: the "pivot" index of this array
"""
1 def pivotIndex(self, nums):
# Write your code here
if nums == []:
return -1
else:
i = 0
sum_1 = 0
sum_2 = sum(nums)
while i < len(nums):
sum_3 =sum_2 - sum_1 - nums[i]
if sum_1 == sum_3:
return i
break
sum_1 += nums[i]
i+=1
if i == len(nums):
return -1