zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    图的广度优先搜索
    图的深度遍历
    图的邻接表的实现
    求1+2!+3!+...+20!的和。
    CSS用户界面样式
    CSS三角
    CSS字体图标技术
    CSS精灵技术
    CSS元素的显示和隐藏
    CSS定位
  • 原文地址:https://www.cnblogs.com/yuanmingzhou/p/9661737.html
Copyright © 2011-2022 走看看