找到第二次出现的索引最小的第一个重复数字 [英] Find the first duplicate number for which the second occurrence has the minimal index

查看:23
本文介绍了找到第二次出现的索引最小的第一个重复数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于代码斗争的问题:

This is a question on codefights:

给定一个数组 a,它只包含从 1 到a.length,找到第一个重复的数字,第二个出现的索引最小.换句话说,如果有更多超过 1 个重复的数字,返回第二个的数字出现的索引小于另一个出现的第二次出现的索引数字是.

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 的值,然后从索引中获取这些值,然后索引中较小的值就是答案.

I've been struggling to figure out how to complete this in python. I'm unsure if I'm on the right path and if I am I can't seem to figure out how to access my index dictionary after finding the specific value from my d dictionary. I want to grab all the values that are greater than one in my d dictionary and then grab those values from index and then whichever value in index is smaller would be the answer.

如果我完全错了,请告诉我.

If I'm going about this completely wrong then please let me know.

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... 简单的方法有什么问题?

Emm... What's wrong with simple approach?

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   

这篇关于找到第二次出现的索引最小的第一个重复数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆