在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:
2 或 3
限制:
2 <= n <= 100000
class Solution {
public int findRepeatNumber(int[] nums) {
Set set = new HashSet();//set集合新建
int repeat = -1;
for (int i = 0; i < nums.length; i++) {
if(set.contains(nums[i])){
//判断集合中是否包含nums
repeat = nums[i];
break;
}
set.add(nums[i]);
}
return repeat;
}
}
解析
最简单的方式就是把数组中的元素一个个加入到集合set中,加入的时候如果有重复的,则直接返回
Set<Integer> set = new HashSet<Integer>();
set是一个接口,不可以直接生成对象,所有使用HashSet,是一个多态
并且set的范型只可以是包装类
其他方法:
先排序在查找,排序之后有重复的肯定是挨着的,然后前后两两比较,如果有重复的直接返回
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);//自带的排序算法
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1])
return nums[i];
}
return -1;
}