Python_Lintcode_1068

本文介绍了一种高效的方法来找到一个整数数组中的“中心”索引,该索引左边所有元素的总和等于其右边所有元素的总和。通过避免重复计算整个数组的总和,此方法显著提高了搜索效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers nums, write a method that returns the "pivot" index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.


求一个数组中左边之和等于右边之和的数的索引值

本来想直接循环加sum(nums[:i])

但是时间复杂度太大,测试只能过40%,然后改啊改

class Solution:
    """
    @param nums: an array
    @return: the "pivot" index of this array
    """
1    def pivotIndex(self, nums):
        # Write your code here
        if nums == []:
            return -1
        else:
            i = 0
            sum_1 = 0
            sum_2 = sum(nums)
            while i < len(nums):
                sum_3 =sum_2 - sum_1 - nums[i]
                if sum_1 == sum_3:
                    return i
                    break
                sum_1 += nums[i]
                i+=1
                if i == len(nums):
                    return -1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值