数组中重复的数字

思路:

以数组{2,3,1,0,2,5,3}为例来分析找重复数字的步骤。

第0个数字是2,与下标不相等,把它和下标为2的数字交换,得到:{1,3,2,0,2,5,3};

第0个数字是1,仍与下标不相等,把它和下标为1的数字交换,得到:{3,1,2,0,2,5,3};

第0个数字是3,仍与下标不相等,把它和下标为3的数字交换,得到:{0,1,2,3,2,5,3};

第0个数字是0,与下标相等,继续下一位;

第1位和1相等,继续下一位;

第2位和2相等,继续下一位;

第3位和3相等,继续;

第4位是2,与下标不相等,要将它和第二位数字交换,但是此时的第二位数字也是2,出现重复的数字了,返回函数,找到重复的数字了。

 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         if(numbers==nullptr || length<=0) return false;
11         for(int i=0;i<length;i++){
12             if(numbers[i]>length-1) return false;
13         }
14         for(int i=0;i<length;i++){
15             while(numbers[i]!=i){
16                 if(numbers[i]==numbers[numbers[i]]){
17                     *duplication = numbers[i];
18                     return true;
19                 }
20                 //交换mubers[i] 和 numbers[numbers[i]]
21                 int temp=numbers[i];
22                 numbers[i]=numbers[temp];
23                 numbers[temp] = temp;
24             }
25         }
26         return false;
27     }
28 };
原文地址:https://www.cnblogs.com/pacino12134/p/11238006.html