赞
踩
Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index’s right.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
First get the sum of the first i-items and last i-items in lsum and rsum, then find the pivot index with sumr[index-1] == rsum[index].
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
nlen = len(nums)
lsum = [0] * (nlen+1)
rsum = [0] * (nlen+1)
for i in range(nlen):
lsum[i+1] = lsum[i] + nums[i]
rsum[nlen-1-i] = rsum[nlen-i] + nums[nlen-1-i]
for i in range(1, nlen+1):
if lsum[i-1] == rsum[i]:
return i-1
return -1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。