package jz03;
import java.util.HashSet;
/**
* @描述 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,
* 但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
* @创建人 jxx
* @创建时间 2021/6/27
* @修改人和其它信息
*/
public class FindRepeatNumber {
public static void main(String[] args) {
int[] arr = {1,2,3,2,1,4,5,4};
System.out.println(findRepeatNumber(arr));
}
/**
* 思路:1.判断值是否存在在set中,存在说明重复了,直接返回,不存在则添加至set中
* @param nums
* @return
*/
private static int findRepeatNumber(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (Integer value : nums) {
if(set.contains(value)) return value;
set.add(value);
}
return -1;
}
}