Topic description
All numbers in an array of length n are in the range 0 to n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated. Also don't know how many times each number is repeated. Find any repeated number in the array. For example, if the input array {2,3,1,0,2,5,3} of length 7, then the corresponding output is the first repeated number 2.
Problem solving ideas
The title does not make it clear:
1. Special attention should be paid here ~ find any repeated value and assign it to duplication[0]
2. The function returns True/False
3. Instead of returning any repeated value, it returns the value in the array first repeated value
Idea 1
Use a dictionary (key-value pairs). It is more intuitive, but the time complexity/space complexity is not low.
def duplicate(self, numbers, duplication):
dict = {}
for num in numbers:
if num not in dict:
dict[num] = 0
else:
duplication[0] = num
return True
return False
Idea 2
There is no need to save additional arrays. The title says "the range of numbers in the array is between 0 and n-1", so you can use the existing array to set the flag. When a number is accessed, you can set the number on the corresponding bit. + n, when you encounter the same number later, you will find that the number in the corresponding bit is greater than or equal to n, so you can directly return this number.
def duplicate(self, numbers, duplication):
long = len(numbers)
for i in range(len(numbers)):
index = numbers[i]%long if numbers[i] >= long else numbers[i]
if numbers[index] > long:
duplication[0] = index
return True
numbers[index] += long
return False