问题描述:
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
思路:
方法一:创建一个容器map,key为出现的数字,value为出现的次数,在遍历数组的过程中,若容器中已经有该数字,那么直接返回给数组,并结束循环。
方法二:让数组的下标与数字相对应,遍历数组,比较当前值与数组下标是否相同。如果不相同,则与数组下标等于当前值得数进行交换,在遍历过程中,若发现需要交换的两个数大小相同,则直接返回给数组,并结束遍历。
代码实现:
方法一:
import java.util.Map;
import java.util.HashMap;
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 这里要特别注意~返回任意重复的一个,赋值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean duplicate(int numbers[],int length,int [] duplication) {
//异常处理
if(numbers==null||numbers.length<=1||length<=1) return false;
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
boolean result = false;
for(int i=0;i<length;i++){
if(!map.containsKey(numbers[i])){
map.put(numbers[i],1);
}else{
duplication[0] = numbers[i];
result = true;
break;
}
}
return result;
}
}
方法二:
import java.util.Map;
import java.util.HashMap;
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 这里要特别注意~返回任意重复的一个,赋值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean duplicate(int numbers[],int length,int [] duplication) {
//异常处理
if(numbers==null||numbers.length<=1||length<=1) return false;
boolean result = false;
for(int i=0;i<length;i++){
if(i != numbers[i]){ //判断当前数组下标和数组的值是否相等
if(numbers[numbers[i]]!=numbers[i]){ //判断两个需要交换的数组的值是否相等
int temp = numbers[numbers[i]];
numbers[numbers[i]] = numbers[i];
numbers[i] = temp;
}else{ //相等则说明找到了重复的数
duplication[0] = numbers[i];
result = true;
}
}
}
return result;
}
}