Python解Leetcode: 724. Find Pivot Index

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

posted @ 2017-11-28 21:34  潇湘旧友  阅读(800)  评论(0编辑  收藏  举报