方法1:
对于重复性问题可以想到set,遍历数组依次加入集合,若集合中存在该元素则直接返回该元素,否则将该元素加入集合:
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @return int整型
*/
public int duplicate (int[] numbers) {
// write code here
Set<Integer> set = new HashSet<Integer>();
for(int i : numbers){
if(set.contains(i)){
return i;
}else{
set.add(i);
}
}
return -1;
}
}方法2:
对于题目所给的条件,可以开辟一个与给定数组等长的新数组,用于记录给定数组中出现的数字的个数(新数组的下标即表示给定数组中的数,数组存放的值,即为该数字出现的次数)一旦新数组中某个记录的数大于1,则返回新数组的下标
代码如下:
public static int duplicate (int[] numbers) {
// write code here
int[] countarray=new int[numbers.length];
for(int i=0;i<numbers.length;i++) {
countarray[numbers[i]]++;
if(countarray[numbers[i]]>1) {
return numbers[i];
}
}
return -1;
}
京公网安备 11010502036488号