转行Java写算法
熟悉基础
哈希集合HashSet
集合,内部元素不重复
Set<String> set = new HashSet<>;
set.add(e);//若e不存在,添加到集合中
set.contains(o);//判断o是否在集合中
set.remove(o);//若o存在,删除
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
int repeat = -1;
for(int num:nums){
if(set.contains(num)) return num;
set.add(num);
}
return -1;
}
}
试图用C++的数组写法,但是java不行,因为ArrayList不能直接用下标访问