面试题3:数组中重复的数字
题目一:找出数组中重复的数字
在一个长度为n的数组里的所有数字都在0~n-1的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3
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) {
//在此编写代码
}
}
对于此问题的一个简单方法就是将此数组进行快速排序,然后判断相邻元素值是否相等,以此来找出存在重复的数值,但是这个方法的空间复杂度为O(nlogn),时间复杂度过高,我们将采用其他简单而又有效的方法去解决此问题。
解法一:我们可以利用hash表的特性去解决这个问题,我们可以遍历数组中的每个元素,然后判断hash表中是否存在此元素,如果不存在,即加入hash表中,如果存在,即找到一个重复的元素,返回此值。这个算法的时间复杂度是O(n),但他提高时间效率是以一个O(n)大小的hash表来作为代价的。
public static boolean duplicate1(int arr[], int len,int [] duplication) {
if (arr == null || len == 0) {
return false;
}
HashSet<Integer> set = new HashSet<Integer>();
for(int i:arr) {
if(!set.contains(i)) {
set.add(i);
}else {
duplication[0] = i;
return true;
}
}
return false;
}
解法二:我们可以使用原地算法,不断在原数组中修正元素的位置,由局部向全局逐渐形成一个排序数组,如果该元素已经在前面的位置出现过,就返回此元素的值。
例如:当我们输入长度为7的数组{2,3,1,0,2,5,3}
我们从下标为0的元素开始,进行局部修正位置
第一次:1 3 2 0 2 5 3
第二次:3 1 2 0 2 5 3
第三次:0 1 2 3 2 5 3
当遍历到第1,2,3个元素,因为下标索引与元素值相等,所以继续往后遍历数组,当遍历到第4个元素的时候,发现2已经出现过,于是便找到所求得值。
public static boolean duplicate2(int arr[], int len,int [] duplication) {
if (arr == null || len == 0) {
return false;
}
int temp = 0;
for (int i = 0; i < len; i++) {
if (arr[i] < i) {
duplication[0] = arr[i];
return true;
}
while (arr[i] != i) {
temp = arr[arr[i]];
arr[arr[i]] = arr[i];
arr[i] = temp;
}
}
return false;
}
解法三:当我们在遍历数组的时候, 对于没有出现过的数字,我们进行加len操作,对于已经出现的数字,其值肯定大于len,返回结果值
public static int duplicate3(int arr[], int len, int[] res) {
if (arr == null || len == 0) {
return -1;
}
int index = 0;
for (int i = 0; i < len; i++) {
index = arr[i] % len;
if (arr[index] > len) {
return index;
}
arr[index] += len;
}
return -1;
}