给定一个整数类型的数组 nums
,请编写一个可以返回数组“中心索引”的方法。python
咱们是这样定义数组中心索引的:数组中心索引的左侧全部元素相加的和等于右侧全部元素相加的和。数组
若是数组不存在中心索引,那么咱们应该返回 -1。若是数组有多个中心索引,那么咱们应该返回最靠近左边的那一个。code
示例 1:索引
输入: nums = [1, 7, 3, 6, 5, 6] 输出: 3 解释: 索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。 同时, 3 也是第一个符合要求的中心索引。
示例 2:io
输入: nums = [1, 2, 3] 输出: -1 解释: 数组中不存在知足此条件的中心索引。
说明:class
nums
的长度范围为 [0, 10000]
。nums[i]
将会是一个范围在 [-1000, 1000]
的整数。时间复杂度:O(n)变量
show me the codeobject
class Solution(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: int """ left_sum ,right_sum = 0,sum(nums) for index, val in enumerate(nums): right_sum -= val if left_sum == right_sum: return index left_sum += val return -1