面试题3:
* 题目:在一个长度为n的数组中的所有数字都在0~n-1的范围内。
* 数组中某一个数字是重复的,但不知道有几个数字重复了,也不知道一个数字重复了几次。
* 请找出数组中任意一个重复的数字。
* 例如输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复数字2或者3。
* 实例:对应的输出的第一个重复的数字是2。
package Test;
public class No3duplicate {
/*
* 面试题3:在一个长度为n的数组中的所有数字都在0~n-1的范围内。
* 数组中某一个数字是重复的,但不知道有几个数字重复了,也不知道一个数字重复了几次。
* 请找出数组中任意一个重复的数字。
* 例如输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复数字2或者3。
* 实例:对应的输出的第一个重复的数字是2。
* */
public static void main(String[] args) {
// TODO Auto-generated method stub
No3duplicate n = new No3duplicate();
int[] arr = {2,3,1,0,2,5,3};
//复杂点,考虑是输入的数组时的情况
int[] duplication = {-1};
boolean b = n.duplicate(arr,arr.length,duplication);
System.out.println(duplication[0]);
}
//输出第一个重复的数字
public boolean duplicate(int numbers[],int length,int[] duplication) {
//判断:若是数组为空或者长度小于0,则直接返回false
if(numbers == null||length < 0) { return false;}
StringBuffer sb = new StringBuffer();
for(int i=0;i<length;i++) {
//判断:若是数值小于0或者数值大于length-1,则直接返回false
if(numbers[i]<0||numbers[i]>length-1) {
return false;
}
//将数据全都添加到sb中
sb.append(numbers[i]+"");
}
for(int i=0;i<length;i++) {
//判断:左侧---numbers[i]字符存在于sb子字符串第一次出现的位置,若有则返回位置下标
// 右侧---numbers[i]字符存在于sb子字符串最后一次出现的位置,若有则返回位置下标
// 若左右想等,表明无重复;若不等,表明该数值重复了,赋值给duplication[0]即为第一次重复的数字
if(sb.indexOf(numbers[i]+"") != sb.lastIndexOf(numbers[i]+"")) {
duplication[0] = numbers[i];
return true;
}
}
return false;
}
}