數組中重複的數

題目:在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是重複的數字2或者3。

思路1:容易想到用Hash數組,即桶排序的思想,申請一個n長度大小的數組,將輸入數組中的元素放入到Hash數組中,然後統計Hash數組中的數個數,如果大於1,表示該下標對應的數字是重複的,易寫出如下代碼

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) {
        //開闢一個length大小的數組當做桶,將輸入數放入相應的桶中
        int *pNumbers = new int[length];
        bool res=false;
        //桶中開始清空
        memset(pNumbers,0,sizeof(int)*length);
        for(int i=0;i<length;i++){
            pNumbers[numbers[i]]++;
        }
        int index=-1;
        for(int i=0;i<length;i++){
            if(pNumbers[i]>1){
                duplication[++index]=i;
                res=true;
            }
        }
        return res;
    }
};
思路1方法中,需要遍歷一次數組,然後遍歷一次Hash數組,O(n)的時間複雜度,但需要O(n)的空間複雜度。想到另一種方法是對輸入的數組進行排序,然後遍歷一次比較前後元素是否相同,即可找出重複的元素
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章