剑指offer 数组中重复的数字

题目描述

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

输入

 

输出

1、从已经排序好的数组中找重复的数字很简单,所以最直接的想法就是先排序。时间复杂度为O(nlogn),空间复杂度为O(1)
2、利用哈希表。从头到尾扫描每一个数字,每扫描一个数字,都可以用O(1)的时间复杂度在哈希表中查看出是否已经包含这个数字。所以时间复杂度为O(n), 空间复杂度为O(n)
3、重排这个数组。从头到尾扫描这个数组,当扫描到下标为 i 的数字时,首先比较这个数字(记为 m )是否与 i 相同,如果是,则接着扫描下一个数字,否则拿它跟第 m 个数字比较。如果它和第 m 个数字相等,则找到重复的数字,否则将第 i 个数字和第 m 个数字交换。接下来重复这个比较、交换的过程,直到发现第一个重复的数字。时间复杂度O(n). 不足之处:改变了数组元素位置。
 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 or length <= 0) {
11             return false;
12         }
13         for (int i = 0; i < length; ++i) {
14             if (numbers[i] < 0 || numbers[i] > length - 1) {
15                 return false;
16             }
17         }
18         for (int i = 0; i < length; ++i) {
19             while (i != numbers[i]) {
20                 if (numbers[i] == numbers[numbers[i]]) {
21                     *duplication = numbers[i];
22                     return true;
23                 }
24                 int tmp = numbers[i];
25                 numbers[i] = numbers[tmp];
26                 numbers[tmp] = tmp;
27             }
28         }
29         return false;
30     }
31 };
 
原文地址:https://www.cnblogs.com/qinduanyinghua/p/10645523.html