1、题目描述
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
2、代码实现
思路:利用 Set 集合不可重复,将数组一个个加入到 Set 集合,加入后判断返回的值,如果为 false 说明存在相同值,即返回该值。
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int num : nums){
boolean add = set.add(num);
if(!add){
return num;
}
}
return -1;
}
}
执行结果
3、思考
如果使用 List 集合就会超出时间限制
public static int findRepeatNumberByList(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
for(int num : nums){
if(list.contains(num)){
return num;
}
list.add(num);
}
return -1;
}
HashSet 底层还是使用的 HashMap,而 HashMap 使用的是链表,所以添加元素快,而且 add() 方法返回值采用 Hash值进行判断,速度较快。