First, the topic
All numbers in an array of length n are within the range of 0 to n-1. Some of the numbers in the array are duplicates, but it is not known that several numbers are duplicates. I don't know how many times each number repeats. Please find any duplicate numbers in the array. For example, if you enter an array of length 7 {2,3,1,0,2,5,3}, the corresponding output is the first repeating number 2.
Second, the idea
Solution One: the solution using Linkedhashmap
Solution Two: See the code (recommended)
Third, the Code
Solution One:
Packagecn1;ImportJava.util.LinkedHashMap;ImportJava.util.Map;ImportJava.util.Set; Public classSolution { Public BooleanDuplicateintNumbers[],intLengthint[] duplication) { Booleanflag=false; if(numbers==NULL|| Length==0){ returnFlag; } //count the number of strings, pay attention to using LinkedhashmapLinkedhashmap<integer, integer> lhm =NewLinkedhashmap<integer, integer>(); for(intnum:numbers) { if(Lhm.containskey (num)) {lhm.put (num, lhm.get (num)+ 1); } Else{lhm.put (num,1); } } //Traverse Map to find the first occurrence of a number intVal=-1; Set<Map.Entry< Integer, integer>> set =Lhm.entryset (); for(map.entry< Integer, integer>Es:set) { intKey =Es.getkey (); intValue =Es.getvalue (); if(Value >= 2) {Val=key; Break; } } if(Val!=-1) {duplication[0]=Val; Flag=true; } //return Results returnFlag; }}
View Code
Solution Two:
Public BooleanDuplicateintNumbers[],intLengthint[] duplication) { Boolean[] k =New Boolean[length]; for(inti = 0; i < k.length; i++) { if(K[numbers[i]] = =true) {duplication[0] =Numbers[i]; return true; } K[numbers[i]]=true; } return false;}
View Code
---------------------------------------------
Reference Links:
Https://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8
The number of duplicates in the array of offer 50