天天看点

Leetcode 724. Find Pivot Index

文章作者:Tyan

博客:noahsnail.com | CSDN | 简书

1. Description

Leetcode 724. Find Pivot Index

2. Solution

**解析:**Version 1,先将数组分为左右两边,左边为

,右边是数组总和,遍历数组,左边加上当前位置的前一个数,右边减去当前位置的数,如果左右相等,返回当前索引,这样优先找到的是满足条件的最左边的索引,最后没找到,返回

-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/