我决定学习python,我使用CodeFight进行训练.第一次采访练习是关于找到数组的第一个副本并返回它或者如果没有则返回-1.这是我写的代码:
def firstDuplicate(a):
b=[]
print(len(a))
for i in range(len(a)):
if a[i] in b:
return(a[i])
elif a[i] not in b and i == (len(a)-1):
return(-1)
else:
b.append(a[i])
Run Code Online (Sandbox Code Playgroud)
我通过除了最后3个以外的所有测试.我说我的程序执行时间超过4000毫秒.我猜数组很长,副本就在最后.如何减少执行时间?提前致谢.