724.中心索引

给定一个整数类型的数组 nums,请编写一个能够返回数组中心索引的方法。

我们是这样定义数组中心索引的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。

如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。

示例 1:

输入:

nums = [1, 7, 3, 6, 5, 6]

输出: 3

解释:

索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。

同时, 3 也是第一个符合要求的中心索引。

 

扫描二维码关注公众号,回复: 3235494 查看本文章
class Solution:
    def pivotIndex(self, list_1):
        """
        :type nums: List[int]
        :rtype: int
        """
        list_sum = 0
        list_reverse_sum = 0
        output_list = []
        dict_1 = {"0":0}
        if len(list_1) == 0:
            return -1
        for i in range(len(list_1)):
            list_sum += list_1[i]
            dict_1[i] = list_sum
        for j in range(len(list_1)-1,-1,-1):
            list_reverse_sum += list_1[j]
            if list_reverse_sum == dict_1[j]:
                output_list.append(j)
        if output_list:
            return min(output_list)
        else:
            return -1

猜你喜欢

转载自www.cnblogs.com/yuanmingzhou/p/9661737.html