剑指offer面试题3-数组中重复的数字

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

解法一:时间复杂度O(n),空间复杂度O(n)

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) {
        /*思路:遍历数组创建map,再遍历map得到第一个重复的数字*/
        
        bool ret;
        //判断输入是否有效
        if (!numbers || length <= 0 || !duplication)
            ret = false;
        
        //创建map
        unordered_map <unsigned, size_t> dupNumber;
        //遍历数组
        for (int i = 0; i < length; ++i) 
            ++dupNumber[numbers[i]];    //若map中存在当前数字则值+1,不存在则创建当前数字的关键字并赋初值为1        
        //查找值大于1的元素并返回其关键字
        for (auto iter = dupNumber.cbegin(); iter != dupNumber.cend(); ++iter) {
            if (iter->second > 1) {
                *duplication = iter->first;
                ret = true;
            }    
        }
        
        return ret;
    }
};

解法二:时间复杂度O(n),空间复杂度O(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) {
        //检查输入参数是否正确
        if (numbers == nullptr || length <= 0) {
            return false;
        }
        //检查是否存在重复数字
        int i = 0;
        while (i < length) {
            if (numbers[i] == i) {    //如果第i个位置上的数值为i,那么继续检测下一个
                ++i;
                continue;
            } else {    //如果第i个位置上的数值不为i,查看该数值m位置上的值是否为m
                int m = numbers[i];
                if (numbers[m] == m) {    //如果为m,那么数字重复
                    *duplication = m;
                    return true;
                } else {    //不为m,则交换值,继续检测下一个
                    numbers[i] = numbers[m];
                    numbers[m] = m;
                    ++i;
                }
            }
        }
        
        return false;
    }
};

 

posted @ 2019-07-01 17:53  zpchya  阅读(255)  评论(0编辑  收藏  举报