剑指offer 数组中重复的数

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

思路:1、暴力法:直接遍历一遍,使用哈希map存储元素,然后找到第一个value值大于1的元素。

2、非常巧妙的方法,剑指offer书上。

1、判断输入数组有无元素非法

2、从头扫到尾,只要当前元素值与下标不同,就做一次判断,numbers[i]与numbers[numbers[i]],相等就认为找到了重复元素,返回true,否则就交换两者,继续循环。直到最后还没找到认为没找到重复元素,返回false 数组中的元素最多只能交换2次就能有序,所以时间复杂度是常数空间复杂度。

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){
            return false;
        }
        for(int i = 0;i < length;++i){
            while(numbers[i] != i){
                if(numbers[i] == numbers[numbers[i]]){
                    * duplication = numbers[i];
                    return true;
                }
                swap(numbers[i],numbers[numbers[i]]);
            }
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7505217.html