数组中重复的数字

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

这道题主要是在思路上要想通。思路就是将每一个数字,放到与它的数值相同的位置上,比如将2放到list[2]上,5放到list[5]上,因为数字的范围在0到n-1之间,所以用数值作为索引不会出现数组越界的情况。这个过程我们可以叫做数字归位,在数字归位的过程中,如果发现当前被归位的数字所在的位置已经有一个值相同的数字存在了,那么,就说明有重复的数字,返回这个数字即可。

思路有了,具体实现很简单。首先我们判断这个数字是不是本来已经在正确的位置,也就是比较 list[i] 与 i 的是否相等。如果相等,则已经归位好了,判断下一个即可。如果没有归位好,那么交换 list[i] 与 list[list[i]]。当然,在交换之前,先判断正确位置是不是已经有这个数了,如果有,返回这个数,如果没有才真正进行交换。

c++代码如下:

 1 class Solution {
 2 public:
 3     // Parameters:
 4     //        numbers:     an array of integers
 5     //        length:      the length of array numbers
 6     //        duplication: (Output) the duplicated number in the array number
 7     // Return value:       true if the input is valid, and there are some duplications in the array number
 8     //                     otherwise false
 9     bool duplicate(int numbers[], int length, int* duplication) {
10         for(int i = 0; i < length; i++){
11             if(numbers[i] != i){
12                 if(numbers[numbers[i]] == numbers[i]){
13                     *duplication = numbers[i];
14                     return true;
15                 }
16                 else swap(numbers[numbers[i]], numbers[i]);
17             }
18         }
19         return false;
20     }
21 };
原文地址:https://www.cnblogs.com/hellosnow/p/12099766.html