Title description
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 do not know how many numbers are repeated. I don't know how many times each number repeats. Please find any duplicate number in the array. For example, if the input array of length 7 is {2,3,1,0,2,5,3}, then the corresponding output is the first repeated number 2.
Problem-solving ideas
The scan array {2,3,1,0,2,5,3} starts with a subscript of 0. If the number of the current position is not equal to its subscript, it will be exchanged with the value of the current element in the table below
- The first time, the subscript is 0, the value is 2. Not equal, exchange with the number 1 with subscript 2 {1,3,2,0,2,5,3}
- The second time, the subscript is 0, the value is 1, not equal to, exchange with the number 3 with subscript 1 {3,1,2,0,2,5,3}
- The third time, the subscript is 0, the value is 3, not equal to, exchange with the number 0 with subscript 3 {0,1,2,3,2,5,3}
- The fourth time, the subscript is 0, the value is 0, equal to, judge the next {1,2,3,2,5,3}
- The fifth time, the subscript is 1, the value is 1, equal to, judge the next {2,3,2,5,3}
- The sixth time, the hem is 2, the value is 2, equal to, judge the next {3,2,5,3}
- The seventh time, the subscript is 3, the value is 3, equal to, judge the next cell {2,5,3}
- The eighth time, the subscript is 4, the value is 2, not equal to, exchange with the subscript 2 number, then the number with subscript 2 is 2, so the first duplicate number is found
Code
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
if(numbers == nullptr || length <= 0)
return false;
for(int i=0;i<length;++i)
{
if(numbers[i]<0 || numbers[i]>length-1)
return false;
}
for(int i=0;i<length;++i)
{
while(numbers[i] != i)
{
if(numbers[i] == numbers[numbers[i]])
{
*duplication = numbers[i];
return true;
}
swap(numbers[i],numbers[numbers[i]]);
}
}
return false;
}
};