繰り返し数の配列を証明する安全性を提供します

タイトル説明

アレイにおけるnの長さの全ての数は、n-1の範囲は0です。一部のデジタル配列が重複しているが、重複しているどのように多くの番号がわかりません。各桁が数回繰り返されるか分からないのです。重複した数字のいずれかの配列を見つけてください。例えば、もし入力アレイ7 {2,3,1,0,2,5,3}の長さは、第2の繰り返し桁の対応する出力。

思考

  1. 暴力的な解決策は、トラバース、真のデジタル複製と繰り返し収益を見つけます
  2. ハッシュ、数が2を超える場合1〜N-1、確立することができるハッシュ・アレイの数は、各番号が出現する回数を保持しているので、繰り返しの説明
  3. 被写体特性は、n桁の使用は、より少ないnより、数が見つかりました。私は番号[i]が、重複を=場合は、返すことができ、私に、すなわち、復帰i番目のデジタル位置、数字に対応する位置に戻すことができます

コード

この方法の一つ:

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

方法2:

class Solution {
public:
    bool duplicate(int numbers[], int length, int* duplication) {
        if(length < 1)
            return false;
        vector<int> Hash(length);
        for(int i = 0; i < length;i++)
        {
            Hash[numbers[i]]++;
        }
        for(int i = 0; i < length;i++)
        {
            if(Hash[i]>1)
            {
                *duplication = i;
                return true;
            }
        }
        return false;
    }
};

方法3:

class Solution {
public:
    bool duplicate(int numbers[], int length, int* duplication) {
        if(length < 1)
            return false;
        int index = 0;
        while(index < length)
        {
            if(numbers[index]== index)
            {
                index ++;
            }
            else
            {
                int tmp = numbers[index];
                if(tmp == numbers[tmp]) // 出现重复
                {
                    *duplication = tmp;
                    return true;
                }
                else //没有重复,则换位置
                {
                    numbers[index] = numbers[tmp];
                    numbers[tmp] = tmp;
                }
            }
        }
        return false;
    }
};
公開された85元の記事 ウォンの賞賛0 ビュー407

おすすめ

転載: blog.csdn.net/weixin_38312163/article/details/104744970