724. Find Pivot Index

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 all the numbers to the left of the index is equal to the sum of all 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.

找到一个位置i使得sum(nums[0:i]) == sum(nums[i + 1:]) 如果有多个,返回最左的i,否则返回-1

这题其实比较简单,求一个左前缀和和右前缀和就可以了,比较恶心的就是边界[1,0,0,-1,1]这个答案是0以及[-1,-1,1,1,1] 答案是4。需要小心一些边界

class Solution(object):
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n < 3:
            return -1
        left = [0] * (n + 2)
        right = [0] * (n + 2)
        for i in range(1, n + 1, 1):
            left[i] = left[i - 1] + nums[i - 1]
        for i in range(n, 0, -1):
            right[i] = right[i + 1] + nums[i - 1]
        for i in range(1, n + 1, 1):
            if left[i - 1] == right[i + 1]:
                return i - 1
        print(left, right)
        return -1
原文地址:https://www.cnblogs.com/whatyouthink/p/13296761.html