剑指offer题目练习
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中第一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是第一个重复的数字2。没有重复的数字返回-1。
如:输入:[2,3,1,0,2,5,3],输出:2
思路一:直接两次循环,每一次的外循环和内循环比较,如果有重复的数字就返回,这样时间复杂度比较高。
public int duplicate (int[] numbers) {
// write code here
System.out.println("llll");
int count=0;
for(int i=0;i<numbers.length;i++){
for(int j=i+1;j<=numbers.length;j++){
if(numbers[i]==numbers[j]){
count=numbers[i];
return count;
}
}
}
return -1;
}
思路二:利用set集合中的值不可以重复的属性,如果添加失败就返回。
public int duplicate (int[] numbers) {
Set<Integer> set =new HashSet<Integer>();
for(int i:numbers){
if(!set.add(i)){
return i;
};
}
return -1;
}