版权声明:欢迎交流,本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42513339/article/details/89292711
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
思路:这里牛客网题目给的函数是 bool duplicate(int numbers[], int length, int* duplication),这里需要判断是否有重复,如果有重复,重复的值赋给 *duplication。
方法有两个,第一个直接用哈希表做映射,遇到为2的直接返回即可。
第二个方法是利用下标和数组下标对应的值,时间复杂度O(n),空间复杂度为O(1);
具体方法如下:
- 输入数组{2,3,1,0,2,5,3};
- 数组下标第一个值,a[0] = 2,下标不等于数组下标值 0,由于题目已经给定了长度为n,所有数字为 0到 n-1,所有直接找 a[2] = 1 ,然后判断 a[2] 是否等于 a[0],若不相等则交换,即数组变成了 {1,3,2,0,2,5,3};
- a[0]下标不等于数组下标值 0,继续判断 a[0] 和 a[a[0]] 即 a[1] 是否相等,若不相等则继续交换,数组变成 {3,1,2,0,2,5,3};
- a[0]下标不等于数组下标值 0,继续判断 a[0] 和 a[a[0]] 即 a[3] 是否相等,若不相等则继续交换,数组变成 {0,1,2,3,2,5,3};
- 由于 a[0] = 0,下标等于数组下标值,所有下标+1继续判断a[1];由于 a[1] = 1,下标等于数组下标值,继续判断a[2],a[3]都相等
- 最后到了 a[4] = 2,而 a[a[4]] = 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 == NULL || length <= 0){
return false;
}
unordered_map<int,int>ans;
for(int i = 0; i<length; i++)
{
ans[numbers[i]]+=1;
if(ans[numbers[i]] == 2){
*duplication = numbers[i];
return true;
}
}
return false;
}
};
方法二:数组下标和数组值判断
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 == NULL || length <= 0){
return false;
}
int i = 0;
while(i != length)
{
if(numbers[i] == i)
i++;
else{
if(numbers[i] == numbers[numbers[i]]){
* duplication = numbers[i];
return true;
}
swap(numbers[i],numbers[numbers[i]]);
}
}
return false;
}
};