题目:题目一:
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
比较容易想到的方法用哈希表存出现过的数,从头到尾遍历一遍,每遍历一个数字都可以判断哈希表中是否包含当前数字。时间复杂度O(n),同时还用了O(n)的空间。
注意到数字都在0-n-1的范围,如果没有重复的数字,排序后,数字i应该正好在下标为i的位置。所以我们从头扫描数组,扫到下标为i的位置时,判断值是否为i,是则扫描下一位;如果不是,比如它为m,我们判断它是否和下标为m的数字相同,相同则说明出现重复数字,不同我们就交换这两个数字,这样m就到了下标为m的位置。重复这个过程就能找到重复的数字。
转自:明光村小队长 来源:CSDN 原文:https://blog.csdn.net/w13261711130/article/details/79973502?utm_source=copy
public class DuplicationInArray {
private int duplicatedNumber;
public boolean findDuplicatedNumber(int[] array, int length) {
if (array == null || length <= 0) throw new IllegalArgumentException("Wrong Arguments");
for (int i = 0; i < length; i++) {
if (array[i] < 0 || array[i] > length -1) throw new IllegalArgumentException("Wrong Numbers in Array");
}
for (int i = 0; i < length; i++) {
while (array[i] != i) {
if (array[i] == array[array[i]]) {
duplicatedNumber = array[i];
//return true; return false; 根据函数的名的意思,做相应的返回
return true;//return 跳出整个函数体findDuplicatedNumber{......},函数体后面的部分不再执行
}
//swap
int temp = array[i];
array[i] = array[temp];
array[temp] = temp;
}
}
return false;return 跳出整个函数体,函数体后面的部分不再执行
}
public static void main(String[] args) {
DuplicationInArray duplicationInArray = new DuplicationInArray();
int[] array = {2,3,1,0,2,5,3};
if(duplicationInArray.findDuplicatedNumber(array,array.length)) System.out.println("find duplicated number is "+ duplicationInArray.duplicatedNumber);
}
}
不能修改数组很容易又想到用哈希表辅助,但是有没有更好的方法?
public class DuplicationInArray {
private int countRange(int[] array,int length,int start,int end){
/**
* 统计该区间有多少个数
*/
if(start<0||end>length-1) throw new IllegalArgumentException("Wrong Arguments");
int count =0;
for(int i=0;i<length;++i){
if (array[i] <= end && array[i] >= start) ++count;}
return count;
}
public int findDuplicatedNumber(int [] array){
int length=array.length;
if(array==null|| length<=0)
throw new IllegalArgumentException("Wrong Arguments");
int start=1;
int end = length-1;
while(end>=start){
int middle=((end-start)>>1)+start;
int count=countRange(array,length,start,middle);//计算start到middle区间的count
if(start==end){
if(count>1) return start;//输出
else break;
}
/**
* 如果数字的数目多于区间长度,说明该区间有重复的数字
* 如果数字的数目多于区间长度,说明该区间有没有重复的数字,重复数字在另一个区间
*/
if(count>middle-start+1) end= middle;
else start =middle +1;
}
return -1;
}
public static void main(String[] args) {
DuplicationInArray duplicationInArray = new DuplicationInArray();
int[] Array={2,3,5,4,3,2,6,7};
System.out.println("find duplicated number is " +duplicationInArray.findDuplicatedNumber(Array));
}
}