3: Repeated numbers in the array

All numbers in an array of length n are in the range of 0 to n-1. Some numbers in the array are repeated, but I do not know how many numbers are repeated. I don't know how many times each number repeats. Please find any duplicate number in the array. For example, if the input array of length 7 is {2,3,1,0,2,5,3}, then the corresponding output is the first repeated number 2.

class solution:
    def duplicate(self,list,duplication):
        for x in range(len(list)):
            while list[x] != x:
                if list[list[x]] == list[x]:
                    duplication.append(list[x])
                    return True
                else:
                    list[list[x]],list[x] = list[x],list[list[x]]
            return False

#In this way, you don't need to open up space and reduce space complexity. Be the most perfect solution

Derivative topics:

What if the array cannot be modified?
1. Use an auxiliary array, but increase the auxiliary space of o (n)
2. Use the method of finding the number: between 1 and n, find the middle number m, divide the original array into two groups, 1 to m and m + 1 to n. In 1 to m, count the total number of occurrences of each number in the original array. If it is greater than m, then there are numbers repeated in 1 to m, and so on, similar to the dichotomy search to find duplicate values

Published 16 original articles · Likes0 · Visits157

Guess you like

Origin blog.csdn.net/qq_43275748/article/details/102657786