面试题03.数组中重复的数字
题目描述
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
题解1
创建一个新的数组,遍历原数组,将得到的值作为新数组的下标,每遍历一个新的数,对应新的数组中,下标为该数的值加一,返回新数组中大于1的数的下标即可
class Solution {
public int findRepeatNumber(int[] nums) {
int[] arr = new int[nums.length];
for(int x=0;x<nums.length;x++){
arr[nums[x]]++;
if(arr[nums[x]]>1)
return nums[x];
}
return -1;
}
}
提交结果
题解2
先对数组进行排序,之后按顺序遍历数组,遇到相同的值返回即可,代码如下:
class Solution {
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
for(int x = 0;x<nums.length-1;x++){
if(nums[x]==nums[x+1])
return nums[x];
}
return -1;
}
}
提交结果
题解3
使用 HashSet 来进行处理,因为 HashSet 本身不允许出现重复元素,所以当添加元素失败或已经包含该数字时,则表示出现了重复元素,将其返回即可,代码如下:
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num: nums) {
if(!set.add(num)) {
return num;
}
}
return -1;
}
}