美文网首页
LeetCode 724. Find Pivot Index

LeetCode 724. Find Pivot Index

作者: 费城的二鹏 | 来源:发表于2018-11-14 14:33 被阅读5次

查找数组重心
思路一 计算左右值 ,循环查找左右值一样的索引

class Solution:
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sum = []
        # print(nums)
        for index in range(len(nums)):
            sum.append({"left": 0, "right": 0})

        for index in range(len(nums)):
            if index > 0:
                sum[index]["left"] = sum[index - 1]["left"] + nums[index - 1]

        for index in range(len(nums), -1, -1):
             if index < len(nums) - 1:
                 sum[index]["right"] = sum[index + 1]["right"] + nums[index + 1]

        # print(sum)

        for index in range(len(nums)):
            if sum[index]["left"] == sum[index]["right"]:
                print(index)
                return index
        print(-1)
        return -1

思路2 直接计算数组总值,遍历时记录左值,计算与右值是否一致

class Solution:
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sumValue = sum(nums)
        leftsum = 0
        for i, n in enumerate(nums):
            leftsum += n
            if leftsum == sumValue - leftsum + n:
                print(i)
                return i
        print(-1)
        return -1

相关文章

网友评论

      本文标题:LeetCode 724. Find Pivot Index

      本文链接:https://www.haomeiwen.com/subject/orcjfqtx.html