美文网首页Leetcode
Leetcode 724. Find Pivot Index

Leetcode 724. Find Pivot Index

作者: SnailTyan | 来源:发表于2021-09-06 10:25 被阅读0次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Find Pivot Index

2. Solution

解析:Version 1,先将数组分为左右两边,左边为0,右边是数组总和,遍历数组,左边加上当前位置的前一个数,右边减去当前位置的数,如果左右相等,返回当前索引,这样优先找到的是满足条件的最左边的索引,最后没找到,返回-1

  • Version 1
class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        left = 0
        right = sum(nums)
        for i in range(len(nums)):
            if i > 0:
                left += nums[i-1]
            right -= nums[i]
            if left == right:
                return i
        return -1

Reference

  1. https://leetcode.com/problems/find-pivot-index/

相关文章

网友评论

    本文标题:Leetcode 724. Find Pivot Index

    本文链接:https://www.haomeiwen.com/subject/zblivltx.html