Title https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
Ideas
1. Use set to be non-repeatable
2. Use map to do
public class N02FindRepeatNumber {
/**
*
* @date: 2020-03-08 22:54
* @param: * @param nums:
* @return: * @return: int
* @author: wwh 2020年03月08日22:54:24--2020年03月08日23:01:01
*
* @Description: 使用set来做
提交2次
==开始写成!=了
执行用时 : 8 ms
内存消耗 :54.3 MB
空间复杂度O(n) 时间复杂度 O(1)
*/
public static int findRepeatNumber(int[] nums) {
if(nums==null||nums.length==0){
return -1;
}
Set set = new HashSet();
for (int num : nums) {
int initSize = set.size();
set.add(num);
if(set.size()==initSize){
return num;
}
}
return -1;
}
/*
*
* @date: 2020-03-10 10:13
* @param: * @param null:
* @return: * @return: null
* @author: wwh
* @Description:执行用时:16 ms 内存消耗:53.4 MB
* 使用map实现 空间复杂度O(n) 时间复杂度O(1)
*/
public static int findRepeatNumber2(int[] nums) {
if(nums==null||nums.length==0){
return -1;
}
Map map = new HashMap();
for (int num : nums) {
if(map.get(num)!=null){
return num;
}
map.put(num, 1);
}
return -1;
}
/**
*
* @date: 2020-03-10 10:14
* @param: * @param args:
* @return: * @return: void
* @author: wwh
* @Description: 先排序
*/
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4, 11, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
System.out.println(findRepeatNumber(arr));
}
}