题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
思考:第一想法是和前面某题类似 利用HashSet 时间复杂度:O(n),空间复杂度:O(n)
//HashMap
public static boolean duplicate2(int numbers[],int length,int [] duplication) {
boolean flag=false;
if(numbers==null||length==0){
return flag;
}
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<length;i++){
if(map.containsKey(numbers[i])){
flag=true;
duplication[0]=numbers[i];
break;
}
map.put(numbers[i], 0);
}
return flag;
}
第二想法 排序 这个太费时 时间复杂度:O(nlogn),空间复杂度:O(1)
第三想法:这个题目的特殊性 即数字皆在0~n-1之间 也就是 若没有重复数据 则是0,1,2,3.......n-1 于是可以让0位上放0 1位上放1 k位上放k........时间复杂度:O(n),空间复杂度:O(1) 还未验证
public static boolean duplicate(int numbers[],int length,int [] duplication) {
if(numbers==null||length==0){
return false;
}
//先判断是否满足大小在0~n-1范围
for(int i=0;i<numbers.length;i++){
if(numbers[i]<0||numbers[i]>=length){
return false;
}
}
for(int i=0;i<numbers.length;i++){
if(i!=numbers[i]&&numbers[i]==numbers[numbers[i]]){
duplication[0]=numbers[i];
return true;
}
while(i!=numbers[i]){
swap(numbers,i,numbers[i]);
}
}
return false;
}
private static void swap(int[] numbers, int i, int j) {
int temp=numbers[i];
numbers[i]=numbers[j];
numbers[j]=numbers[i];
}
参考:https://www.cnblogs.com/AndyJee/p/4693099.html
https://blog.csdn.net/ouyangyanlan/article/details/72897378?locationNum=6&fps=1