简体   繁体   English

如何找出列表中第一个重复的数字?

[英]How to find out the first duplicated number in a list?

I need to find out the first duplicated number in a list (the index of the second occurrence must be the smallest).我需要找出列表中第一个重复的数字(第二次出现的索引必须是最小的)。 Here is my code:这是我的代码:

def firstDuplicate(a):
    b = []
    for i in range(len(a)):
        for j in range(i+1, len(a)):
            if a[i] == a[j]:
                b.append(j)
                if len(b) == 0:
                    return -1
                else:
                    return a[min(b)]

for example if I have a = [2, 1, 3, 5, 3, 2], it should return 3, but it returns 2 instead.例如,如果我有一个 = [2, 1, 3, 5, 3, 2],它应该返回 3,但它返回 2。 I verified with this code:我用这个代码验证:

a = [2, 1, 3, 5, 3, 2]

b = []
for i in range(len(a)):
    for j in range(i+1, len(a)):
        if a[i] == a[j]:
            b.append(j)
print(b)

it turned out with the correct answer which is [5,4].结果是正确的答案是 [5,4]。 So I don't know what's wrong here.所以我不知道这里出了什么问题。 Can anybody help?有人可以帮忙吗? Thanks!!谢谢!!

Here is the screenshots:以下是截图: 在此处输入图片说明 在此处输入图片说明

Everytime the condition a[i] == a[j] is met, you are returning and stoping the loop.每次满足条件a[i] == a[j]时,您都在返回并停止循环。 Return after the loop is finished:循环结束后返回:

def firstDuplicate(a):
    b = []
    for i in range(len(a)):
        for j in range(i+1, len(a)):
            if a[i] == a[j]:
                b.append(j)
    if len(b) == 0:
        return -1
    else:
        return a[min(b)]

print(firstDuplicate([2, 1, 3, 5, 3, 2]))

Out:出去:

3

It seems you have written return condition inside for loop.您似乎在 for 循环中写入了返回条件。 So it returning on first iteraton.所以它在第一次迭代时返回。 Try this尝试这个

def firstDuplicate(a):
    b = []
    for i in range(len(a)):
        for j in range(i+1, len(a)):
            if a[i] == a[j]:
                b.append(j)
    if len(b) == 0:
        return -1
    else:
        return a[min(b)]

I think we can identify duplicate with single iteration of array.我认为我们可以通过数组的单次迭代来识别重复项。

def first_duplicate(arr):
    d = dict()
    n = len(arr)
    for i, v in enumerate(arr):
        if v in d:
            d[v] = i
        else:
            d[v] = n

    # print(d)
    return min(d, key=d.get)


arr = [2, 1, 3, 5, 3, 2]
print(first_duplicate(arr))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM