【题目】
给你一个整数数组 nums,请编写一个能够返回数组 “中心下标” 的方法。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果数组不存在中心下标,返回 -1 。如果数组有多个中心下标,应该返回最靠近左边的那一个。
注意:中心下标可能出现在数组的两端。
【示例 1】
输入:nums = [1, 7, 3, 6, 5, 6]
输出:3
解释:
中心下标是 3 。
左侧数之和 (1 + 7 + 3 = 11),
右侧数之和 (5 + 6 = 11) ,二者相等。
【示例 2】
输入:nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心下标。
【示例 3】
输入:nums = [2, 1, -1]
输出:0
解释:
中心下标是 0 。
下标 0 左侧不存在元素,视作和为 0 ;
右侧数之和为 1 + (-1) = 0 ,二者相等。
【提示】
nums 的长度范围为 [0, 10000]。
任何一个 nums[i] 将会是一个范围在 [-1000, 1000]的整数。
【代码】

class Solution:
def pivotIndex(self, nums: List[int]) -> int:
l2r=dict()
l=len(nums)
if l==0:
return -1
s=0
for i in range(0,l):
s+=nums[i]
l2r[i]=s
for i in range(l):
if (i==0 and s-nums[i]==0) or (i and s-l2r[i]==l2r[i-1]) or (i==l-1 and s-nums[i]==0):
return i
return -1
【方法2:一次遍历】

class Solution:
def pivotIndex(self, nums: List[int]) -> int:
s=sum(nums)
l=len(nums)
all=0
for i in range(l):
all+=nums[i]
if (i==0 and s-nums[i]==0) or (i and s-all==all-nums[i]) or (i==l-1 and s-nums[i]==0):
return i
return -1
【方法3:数学法+一次遍历】

class Solution:
def pivotIndex(self, nums: List[int]) -> int:
total=sum(nums)
l=len(nums)
s=0
for i in range(l):
if 2*s+nums[i]==total:
return i
s+=nums[i]
return -1
3688



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



