1. Subject requirements
All numbers in an array nums of length n are in the range of 0~n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated, and I don't know how many times each array is repeated. Please find any duplicate number in the array.
输入: [2,3,1,0,2,5,3]
输出:2 或 3
2. Problem solving ideas
method one
In Java, we can achieve this through the Hash table, and then use the loop to add the elements in the array to the Hash table. When the repeated number appears for the second time, the return value of add(num) will be false. This is what we do. You can return the duplicate value back.
Method Two
The second method is to achieve by exchanging subscripts, which is also a more commonly used method.
3. Code implementation
method one
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;
}
Method Two
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;
}
}