leetcode 724. Find Pivot Index

  • 题目描述:在数组中找到一个值,使得该值两边所有值的和相等。如果值存在,返回该值的索引,否则返回-1

  • 思路:遍历两遍数组,第一遍求出数组的和,第二遍开始,保存左边所有的值的和,当左边值的和的2倍加上当前值等于数组和时,就是要找的索引。时间复杂度为o(n),空间复杂度为o(1).

class Solution(object):
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ret = sum(nums)
        left = 0
        for k, v in enumerate(nums):
            if left * 2 + v == ret:
                return k
            left += v
        return -1

相关文章:

  • 2021-07-11
  • 2021-12-19
  • 2021-10-07
  • 2022-12-23
  • 2022-02-23
  • 2022-12-23
  • 2021-12-19
  • 2022-01-18
猜你喜欢
  • 2021-12-10
  • 2022-12-23
  • 2021-05-26
  • 2022-12-23
  • 2021-12-18
  • 2021-08-17
  • 2021-10-18
相关资源
相似解决方案