1、题目要求
在一个长度为n的数组nums里的所有数字都在0~n-1的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数组重复了几次。请找出数组中任意一个重复数字。
输入: [2,3,1,0,2,5,3]
输出:2 或 3
2、解题思路
方法一
Java我们可以通过Hash表来实现,再用循环去将数组中的元素添加到Hash表中,当重复数字出现第二次添加的时候,add(num)返回的就会是false,这是我们就可以将重复值返回回去。
方法二
第二种方法就是通过交换下标的方式来实现,也是比较常用的方式。
3、代码实现
方法一
public static void main(String[] args) {
int[] sums = {
2,3,1,0,2,5,3};
int x = new demo_1().HashMethod(sums);
System.out.println(x); //输出: 2
}
/**
* 方法一 使用Hash表
*
*/
public int HashMethod(int[] nums) {
int res = -1;
Set<Integer> set = new HashSet<Integer>();
for(int num : nums){
if(!set.add(num)) {
res = num;
break;
}
}
return res;
}
方法二
public static void main(String[] args) {
ArrayRechecking aim = new ArrayRechecking();
int[] numbers={
5,1,2,3,2,1,4};
int length=7;
int[] duplication=new int[1];
boolean aa = aim.ArrayIndexMethod(numbers, length, duplication);
System.out.println(aa + " "+ duplication[0]);
}
class ArrayRechecking{
public boolean ArrayIndexMethod(int[] nums,int length,int[] Dvalue) {
// 判断数组和长度是否为空
if(nums == null|| length<=0) {
return false;
}
// 排除不符合题意的部分
for(int i=0; i<length;i++) {
if(nums[i]<0 || nums[i]>=length) {
return false;
}
}
for(int i=0; i<length;i++) {
while(nums[i] != i) {
if(nums[i] == nums[nums[i]]) {
// true说明有重复
Dvalue[0] = nums[i]; // 将重复值赋给数组存储
return true;
}
int temp = nums[i];
nums[i] = nums[temp];
nums[temp] = temp;
}
}
return false;
}
}