python - 查找第二次出现的索引最小的第一个重复数字

标签 python algorithm python-2.7 dictionary data-structures

这是一个关于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/

相关文章:

javascript - 检查公民号码的算法

python - Python中的前序遍历

python - 使用列表根据多列中的值有条件地填充新列

python - 编写函数以传递参数或参数元组的大多数 pythonic 方式

python - 如何在 Python 3 中使用 cmp()?

Python 与 SQL 数据库的链接

java - 0-1 背包实现产生错误答案

python - Pandas:欧式date_range

Python 日期时间 : All Items From Yesterday

python - 如何将 __len__ 添加到数据类型定义中没有 __len__ 的对象?