【阿里巴巴找黄金宝箱】Python

 难度指数:⭐⭐

通用一般算法:

华为od统一考试B卷【阿里巴巴找黄金宝箱】Python 实现 

def solve(nums):
    sum_left, sum_right = 0, sum(nums)
    for i in range(len(nums)):
        sum_right -= nums[i]
        # 若左侧元素和等于右侧元素和,返回中心下标 i
        if sum_left == sum_right:
            return i
        sum_left += nums[i]
    return -1

我的算法

代码实现

def solve0(nums):
    nums = [0] + nums
    total = sum(nums)
    temp = 0
    for i in range(1, len(nums)):
        temp += nums[i - 1] + nums[i]
        if temp == total:
            return i - 1
    return -1

对比验证

from time import time
import random
 
def solve(nums):
    sum_left, sum_right = 0, sum(nums)
    for i in range(len(nums)):
        sum_right -= nums[i]
        # 若左侧元素和等于右侧元素和,返回中心下标 i
        if sum_left == sum_right:
            return i
        sum_left += nums[i]
    return -1

def solve0(nums):
    nums = [0] + nums
    total = sum(nums)
    temp = 0
    for i in range(1, len(nums)):
        temp += nums[i - 1] + nums[i]
        if temp == total:
            return i - 1
    return -1

T = 10
while T:
    nums = [random.randint(-1e3, 1e3) for _ in range(random.randint(1, 1e4))]
    t1 = time() 
    res = solve0(nums)
    t2 = time()
    time()
    time()
    res0 = solve(nums)
    t3 = time()
    if res != res0:
        print(res, res0)
    print(t2 - t1, t3 - t2)
    T -= 1

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>