题目
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
分析
这道题是比较基础,主要思路如下:
- 首先判断数组是否为空,若为空直接返回false;
- 然后初始化集合及其对应哈希表,利用哈希表统计每个元素出现的次数;
- 之后遍历整个集合,获取第一个出现次数大于1的元素,并将其加入重复数组,最终返回true,若无则直接返回false;
github链接:JZ50-数组中重复的数字
C++代码
#include <iostream>
#include <map>
#include <set>
#include <cstring>
using namespace std;
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;
}
map<int,int> number_hash;
set<int> number_set;
for(int i = 0 ; i < length ; i++){
number_hash[numbers[i]]++;
number_set.insert(numbers[i]);
}
int cnt = 0;
set<int>::iterator it;
for(it = number_set.begin() ; it != number_set.end() ; it++){
if(number_hash[*it] > 1){
duplication[cnt++] = *it;
return true;
}
}
return false;
}
};
int main()
{
int n;
Solution s;
while(cin>>n){
int* array = new int[n];
int* duplication = new int[n];
memset(array,0,sizeof(int)*n);
memset(duplication,0,sizeof(int)*n);
for(int i = 0; i < n ; i++){
cin>>array[i];
}
bool flag = s.duplicate(array,n,duplication);
if(flag){
for(int i = 0 ; i < n ; i++){
cout<<duplication[i]<<" ";
}
cout<<endl;
}
}
return 0;
}