50:数组中重复的数字
题目描述
描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任一一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1
问题解析
如题可知 数组中的数字大小不会超过数组的长度,所以可以用数组来实现,创建一个空数组与原数组长度相同,遍历元数组,使得新数组中原数组中值对应的下标位置的值+1;当对应下表值为2的时候 ,返回该值 若没有 返回-1
代码实现
package com.xu.fingeroffer.fifty;
import java.util.HashMap;
public class 数组中重复的数组50 {
public static void main(String[] args) {
int []a = {2,1,3,1,4};
System.out.println(duplicate2(a));
}
public static int duplicate (int[] numbers) {
if(numbers==null||numbers.length==0){
return -1;
}
// write code here
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if(map.get(numbers[i])==null){
map.put(numbers[i],1);
}else {
return numbers[i];
}
}
return -1;
}
/**
* 解法二
* @param numbers
* @return
*/
public static int duplicate2 (int[] numbers) {
int []test = new int [numbers.length];
for (int i = 0; i < numbers.length; i++) {
test[numbers[i]]++;
if(test[numbers[i]]==2){
return numbers[i];
}
}
return -1;
}
}