难度指数:⭐⭐
通用一般算法:
华为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