Title: 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.
https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=3&rp=2 &ru=%2fta%2fcoding-interviews&qru=%2fta%2fcoding-interviews%2fquestion-ranking
Ideas:
The value is placed under the corresponding subscript, if the corresponding subscript element and the value are equal, repetition occurs.
Note: Check the value of the array within 0-n-1
Public classSolution {//Parameters://numbers:an array of integers//length:the length of array numbers//duplication: (Output) The duplicated number in the array number,length of duplication array is 1,so using Duplicat Ion[0] =? in implementation; //Here duplication-like Pointor-C + +, duplication[0] equal *duplication in C/C + +//here to pay special attention ~ return any duplicate one, assignment value duplication[0]//Return Value:true If the input is valid, and there be some duplications in the array number//otherwise false Public BooleanDuplicateintNumbers[],intLengthint[] duplication) { //way1. Sort and then Traverse time O (nlogn)//Time of Way2.hashmap,o (n), Space of O (n)//Way3. Iterates over the array and compares the current subscript, and swaps the number to be placed below the subscript until it finds duplicates. O (n) time, O (1) of the space if(Numbers = =NULL|| Numbers.length = = 0) { return false; } for(inti = 0; i < numbers.length; i++) { //The numbers are within the range of 0 to n-1. if(Numbers[i] < 0 | | numbers[i] >=numbers.length) {return false; } } for(inti = 0; i < numbers.length; i++) { //if the current value and subscript are equal, the next if(Numbers[i] = =i) {Continue; } //The current value and subscript are not equal, and it is found that the current value and the value for the underlying are identical, and the number of duplicates is found if(Numbers[i] = =Numbers[numbers[i]]) {duplication[0] =Numbers[i]; return true; } //Place the current value at the corresponding subscript position inttemp =Numbers[i]; Numbers[i]=Numbers[temp]; Numbers[temp]=temp; } return false; }}
View Code
Test: There are no duplicate elements, duplicate elements are multiple, duplicate elements are maximum or minimum; array elements are not 0-n-1
51, the number of repetitions in the array