天天看點

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/