题目:有一个长度为n的数组,里面所有元素的值都为整数,且范围为0到n-1。请输出任意一个重复的数字,即判断数字是否重复即可。
例:
输入数组:{ 1, 6, 5, 3, 12, 2, 3, 2, 0, 1, 7, 4, 5 }
例:
输入数组:{ 1, 6, 5, 3, 12, 2, 3, 2, 0, 1, 7, 4, 5 }
打印出1、5、3、2任意一个即可。
方法有如下三种:
一、用一个额外的数组记录重复情况,因为元素的值不可能超过下标,所以可以把元素的值当作额外数组的下标,如果该下标已被标记,则打印出重复的数字。
代码如下:
public static void printDuplicationByOtherArray(int[] testArray) {
if (testArray == null || testArray.length == 0) {
return;
}
checkArrayFormat(testArray);
int length = testArray.length;
int[] duplicatedCount = new int[length];
for (int i = 0; i < length; i++) {
int index = testArray[i];
if (duplicatedCount[index] != 0) {
System.out.println("Duplicated value " + index);
return;
}
duplicatedCount[index] = duplicatedCount[index] + 1;
}
}
测试代码如下:
public static void main(String[] args) {
int[] testArray = new int[] { 1, 6, 5, 3, 12, 2, 3, 2, 0, 1, 7, 4, 5 };
printDuplicationByOtherArra