这是一个关于codefights的问题:
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does.
我一直在努力弄清楚如何在 python 中完成它。我不确定我是否在正确的道路上,如果我是,我似乎无法弄清楚如何在从我的 d 字典中找到特定值后访问我的索引字典。我想在我的 d 字典中获取所有大于 1 的值,然后从索引中获取这些值,然后索引中较小的值就是答案。
如果我的做法完全错误,请告诉我。
def firstDuplicate(a):
d = {}
index = {}
for i in a:
if i in d:
d[i] += 1
else:
d[i] = 1
for i,e in enumerate(a):
if e in d:
index[e] = i
else:
index[e] = i
for key,val in d.items():
if val > 1:
最佳答案
Emm...简单的方法有什么问题?
def firstDuplicate(a):
aset = set()
for i in a:
if i in aset:
return i
else:
aset.add(i)
print(firstDuplicate([7,4,5,6,4,6,3]))
词典版:
adict = {}
for i in a:
if i in adict:
return i
else:
adict[i] = 1
关于python - 查找第二次出现的索引最小的第一个重复数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45114203/