724.中心索引

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

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

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

示例 1:

输入:

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

输出: 3

解释:

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

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

 

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

 

转载于:https://www.cnblogs.com/yuanmingzhou/p/9661737.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值