剑指 Offer 03. 数组中重复的数字

转载自Leet Code《剑指Offer》

题目描述

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。 数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。 请找出数组中任意一个重复的数字。

示例

输入:[2, 3, 1, 0, 2, 5, 3] 输出:23

提示:

  • 2 <= n <= 100000

我的代码

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
class MySolutionOffer03 {
public int findRepeatNumber(int[] nums) {
if (nums.length<=2) return nums[0];
HashSet<Integer> set = new HashSet();
for (int num:nums)
if (set.contains(num)) return num;
else set.add(num);
return -1;
}
}