简体   繁体   中英

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. 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]. 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. 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. 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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