【剑指offer】数组中重复的数字

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
 
思路:
这道题是做过的,但是时间久了,忘记了....
自己读题也不仔细,没注意到数字都在0-n-1范围内....
 
首先,上最好的方法吧。O(N)时间+O(1)空间的
思路是:把数组中的下标和数字对应起来,举例,让numbers[0]中的数字是0,让numbers[1]中的数字是1....
如果说下标已经和数字对应了,又找到了相同的数字就是出现了重复。
由于每个数字只会归位一次,所以是O(N)的算法。
bool duplicate3(int numbers[], int length, int* duplication)
    {
        if(numbers == NULL) return false;
        for(int i = 0; i < length; i++)
        {
            while(numbers[i] != i) //当前位与数字不匹配
            {
                if(numbers[i] == numbers[numbers[i]])
                {
                    duplication[0] = numbers[i];
                    return true;
                }
                else  //把当前位存储的数字放入正确的位置
                {
                    swap(numbers[i], numbers[numbers[i]]);
                }
            }
        }
        return false;
    }

用hashtable的方法 时间O(N)空间O(N)

bool duplicate(int numbers[], int length, int* duplication) {
        unordered_set<int> us;
        for(int i = 0; i < length; i++)
        {
            if(us.find(numbers[i]) == us.end())
            {
                us.insert(numbers[i]);
            }
            else
            {
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
    }

排序的方法

static int cmp(const void *a, const void * b)
    {
        return *(int *)a - *(int *)b;
    }
    bool duplicate2(int numbers[], int length, int* duplication) {
        qsort(numbers, length, sizeof(int), cmp);
        for(int i = 1; i < length; i++)
        {
            if(numbers[i] == numbers[i - 1])
            {
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
    }
原文地址:https://www.cnblogs.com/dplearning/p/4673080.html