首页 > 其他 > 详细

724. Find Pivot Index

时间:2020-07-14 01:14:51      阅读:65      评论:0      收藏:0      [点我收藏+]

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

 

724. Find Pivot Index

原文:https://www.cnblogs.com/whatyouthink/p/13296761.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!