剑指Offer刷题——数组类
03,easy
找出数组中重复的数字
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
- 方法一. 利用Arrays.Sort()方法排序,比较相邻两个数字
public static int findRepeatNumber(int []nums){
Arrays.Sort(nums);
for(int i = 0; i< nums.length; i++){
if(nums[i] == nums[i+1])
return nums[i];
}
return -1;
}
- 方法二. 把数组元素赋给新数组的索引,如果个数>1,则返回-1
public static int findRepeatNumber(int []nums){
int[] newNum = new int[nums.length];
for(int i : nums){
if(++newNum[i] > 1)
return i;
}
return -1;
}
- 方法三. 新建Set集合,利用Set的无序不可重复性,如果不能添加此元素,说明重复,返回此元素
public static int findRepeatNumber(int []nums){
HashSet<Integer> set = new HashSet<>();
for(int i : nums){
if(!set.add(i))
return i;
}
return -1;
}