Sword counts repeated numbers in a group

topic link

When I encounter this kind of problem, my first reaction is map every time. It's too difficult for me.

Of course, it can be done by opening a bool to make a vis tag. Here is an unexpected practice in the record discussion.

 

If you encounter this number once, add length. If you encounter this number later, it is already greater than length, then it must have been repeated before.

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(length == 0) return false;
        for(int i = 0; i < length; i++) {
            int index = numbers[i];
            if(index >= length) {
                index -= length;
            }
            if(numbers[index] >= length) {
                *duplication = index;
                return true;
            }
            numbers[index] += length;
            
        }
        return false;
    }
};

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326574029&siteId=291194637