本题用到了hashSet去重原理。
首先hashSet的特点:无序的,不允许重复,底层数据结构是哈希表(它是基于hashMap实现的)。
hashSet保证元素唯一性:依赖于hashCode()和equals()方法,在他的add方法中,添加了要添加对象再集合中是否存在,即迭代集合中的每个元素,和要添加的相比较,如果相同就不存。
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set=new HashSet<Integer>();
int repeat=-1;
for(int num:nums){
if(!set.add(num)){
repeat=num;
break;
}
}
return repeat;
}
}