一、问题
1、在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
2、例子
输入:[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
3、限制
2 <= n <= 100000
package com.haoxiansheng.demo01.SwordfingerOffer;
import lombok.extern.slf4j.Slf4j;
import java.util.HashSet;
import java.util.Set;
/**
* @author flame
* @data 2020/10/13
*/
@Slf4j
public class FindRepeatNumber {
public static void main(String[] args) {
int[] ints = {
1, 2, 3, 1, 3, 4, 5, 6, 6, 3, 7};
log.info("findRepeatNumber=>{}", findRepeatNumber(ints));
log.info("findRepeatNumbers=>{}", findRepeatNumbers(ints).toString());
}
/**
* 找出任意重复的数字
*
* @param nums
* @return
*/
public static int findRepeatNumber(int[] nums) {
Set<Integer> temp = new HashSet<>();
int repeat = -1;
for (int num : nums) {
if (!temp.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
/**
* 找出所有重复的 数字
*
* @param nums
* @return
*/
public static Set<Integer> findRepeatNumbers(int[] nums) {
Set<Integer> result = new HashSet<>();
Set<Integer> temp = new HashSet<>();
for (int num : nums) {
if (!temp.add(num)) {
result.add(num);
}
}
return result;
}
}