剑指offer——数组中重复的数字
问题描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2
思路分析
1.先判断数组是否为空,若是,则返回这个false。并且判断数字是否在0到n-1的范围内
2.排序。
—从头到尾扫描排序后的数组,排序长度为n的数组时间复杂度O(nlogn)。
—利用hash表,每扫描到一个数字的时候,用O(1)的时间来判断哈希表是否包含这个数字,排序长度为n的数组时间复杂度O(n),提高效率的代价是一个空间复杂度为O(n)的哈希表。
—本解法寻求时间复杂度为O(n),的算法,空间复杂度为O(1)。
3.具体操作如下:
如: 长度为7的数组{2,3,1,0,2,5,3}
数组 {2, 3, 1, 0, 2, 5, 3}
下标 [0, 1, 2, 3, 4, 5, 6]
扫描: 第一个元素2不等于下标0,将2与下标为2的数字交换
数组 {1, 3, 2, 0, 2, 5, 3}
下标 [0, 1, 2, 3, 4, 5, 6]
扫描: 第一个元素1不等于下标0,将1与下标为1的数字交换
数组 {3, 1, 2, 0, 2, 5, 3}
下标 [0, 1, 2, 3, 4, 5, 6]
扫描: 第一个元素3不等于下标0,将3与下标为3的数字交换
数组 {0, 1, 2, 3, 2, 5, 3}
下标 [0, 1, 2, 3, 4, 5, 6]
扫描: 发现前四个元素对应,扫描下标为4的数字2,数值和下标不相等。
再比较2和下标为2的数字,发现2,4两个位置都是2,所以重复。
代码
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<=0){
return false;
}
for(int i=0;i<numbers.length;++i){
if(numbers[i]<=0||numbers[i]>numbers.length-1){
return false;
}
}
for(int i=0;i<numbers.length;++i){
while(numbers[i]!=i) {
if (numbers[i] == numbers[numbers[i]]) {
duplication[0] = numbers[i];
return true;
}
int temp = numbers[i];
numbers[i] = numbers[temp];
numbers[temp] = temp;
}
}
return false;
}
}