剑指offer——数组中重复的数字

题目描述:
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

思路1:
使用hashTable,以空间换时间

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

思路2:本题不允许修改原数组,如果可以修改原数组的话,可以先对数组进行排序,然后通过前后元素比较,查找到排序后第一个重复的数字

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章