剑指 Offer 03. 数组中重复的数字
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
看成了找出数组任何一个重复数字
看错题做的垃圾版:
public static int findRepeatNumber(int[] nums) {
Map <Integer,Integer> integerMap=new HashMap<Integer, Integer>();
Set<Integer> result= new HashSet<>();
for (int j : nums) {
integerMap.put(j, integerMap.getOrDefault(j, 0) + 1);
}
for (int num : nums) {
if (integerMap.get(num) >= 2) {
return num;
}
}
return 0;
}
执行用时:16 ms, 在所有 Java 提交中击败了5.28%的用户
内存消耗:48 MB, 在所有 Java 提交中击败了22.77%的用户
企业级:
public static 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;
}
执行用时:5 ms, 在所有 Java 提交中击败了49.66%的用户
内存消耗:48.1 MB, 在所有 Java 提交中击败了21.53%的用户