Repeated numbers in the array of "Sword Finger Offer"
I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
Problem : 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 don't know how many numbers are repeated. I don’t know how many times each number is repeated. Please find the first repeated number in the array. For example, if the input length is 7 array [2,3,1,0,2,5,3], then the corresponding output is the first repeated number 2. Return -1 if there is no repeated number.
Example :
示例 1 :
输入:[2,3,1,0,2,5,3]
返回值:2
Code 1:
classSolution:defduplicate(self , numbers ):
temp =0
d ={
}for i inrange(len(numbers)):
d[numbers[i]]= d.get(numbers[i],0)+1if d[numbers[i]]==2:return numbers[i]return-1
Algorithm description: Create a dictionary, traverse the elements in the array one by one, store the number of elements in the dictionary, and return the current element when the number of elements exceeds 2.