Title Descriptionall 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}, then the corresponding output is a repeating number of 2 or 3.
"Idea 1" requires a container to store numbers that are not duplicated, and returns if the same number is found in the container during a backward traversal.
1 classSolution {2 Public:3 //Parameters:4 //numbers:an array of integers5 //length:the length of array numbers6 //duplication: (Output) The duplicated number in the array number7 //Return Value:true If the input is valid, and there be some duplications in the array number8 //otherwise false9 BOOLDuplicateintNumbers[],intLengthint*duplication) {Ten if(numbers = = NULL)return false; Onevector<int>Vec; A intCount =0; - for(inti =0; i < Length;i + +){ - if(Numbers[i] <0|| Numbers[i] > Length-1)return false; the if(Find (Vec.begin (), Vec.end (), numbers[i])! =Vec.end ()) { -duplication[0] =Numbers[i]; - return true; -}Else{ + Vec.push_back (Numbers[i]); - } + } A if(duplication[0] == -1)return false; at Else return true; - } -};
"Train of thought 2" does not need an extra array to save, the topic is written in the array of numbers in the range guaranteed between 0 ~ n-1, so you can use the existing array to set the flag, when a number is accessed, you can set the corresponding bit on the number + N, and then encounter the same number, you will find that the number of the corresponding bit Then return this number directly.
1 classSolution {2 Public:3 //Parameters:4 //numbers:an array of integers5 //length:the length of array numbers6 //duplication: (Output) The duplicated number in the array number7 //Return Value:true If the input is valid, and there be some duplications in the array number8 //otherwise false9 BOOLDuplicateintNumbers[],intLengthint*duplication) {Ten if(numbers = = NULL)return false; One for(inti =0; i < Length;i + +){ A intindex =Numbers[i]; - if(Index >=length) { -Index-=length; the } - if(Numbers[index] >=length) { -duplication[0] =index; - return true; + } -Numbers[index] + =length; + } A return false; at } -};
[Sword means offer] 50. Repeated numbers in the array