Leetcode

Leetcode 724. Find Pivot Index

2021-09-06  本文已影响0人  SnailTyan

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

1. Description

Find Pivot Index

2. Solution

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

猜你喜欢

热点阅读