Cattle off network - prove safety office- array duplicate numbers

Title : all numbers in an array of length n's are in the range of 0 to n-1. Some digital array is duplicated, but do not know how many numbers are duplicated. Do not know each digit is repeated several times. Please find an array of any one of the duplicate numbers. For example, if the length of the input array 7 {2,3,1,0,2,5,3}, then the corresponding output of the first 2 repeating digits.
Idea : We can start from scratch each scan this array of numbers. When the scanner is small labeled i digital, the digital and comparing the first (indicated by m) and if i is equal. If so, scan the next number. If not, the comparison and the subscript m is a number m are equal, if equal, to find a duplicate numbers. If not equal, the exchange sequence between. To repeat the above steps.

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)
                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;
    }
};

Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91381138