查找数组重心
思路一 计算左右值 ,循环查找左右值一样的索引
class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum = []
# print(nums)
for index in range(len(nums)):
sum.append({"left": 0, "right": 0})
for index in range(len(nums)):
if index > 0:
sum[index]["left"] = sum[index - 1]["left"] + nums[index - 1]
for index in range(len(nums), -1, -1):
if index < len(nums) - 1:
sum[index]["right"] = sum[index + 1]["right"] + nums[index + 1]
# print(sum)
for index in range(len(nums)):
if sum[index]["left"] == sum[index]["right"]:
print(index)
return index
print(-1)
return -1
思路2 直接计算数组总值,遍历时记录左值,计算与右值是否一致
class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sumValue = sum(nums)
leftsum = 0
for i, n in enumerate(nums):
leftsum += n
if leftsum == sumValue - leftsum + n:
print(i)
return i
print(-1)
return -1
网友评论