​welcome to my blog​

剑指offer面试题3(java版):数组中重复的数字

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

思路

  • 逐个位置判断, 对于当前位置i, 要么numbers[i] == i; 要么numbers[i] != i
  • 如果numbers[i] != i, 要么numbers[numbers[i]] == numbers[i], 返回true; 要么numbers[numbers[i]] != numbers[i], 交换索引为i和索引numbers[i]对应的值
  • 所有位置遍历完之后如果没有返回true, 则说明没有重复的数字, 返回false

复杂度

  • 时间复杂度: 虽然使用了两层循环,但是每个数字最多交换两次就能处于正确的位置上,所以时间复杂度为O(n)
  • 空间复杂度: 没有使用额外的内存空间,所以空间复杂度为O(1)

第二次做, 如果数组中没有重复的数,那么0…n-1这n个数都可以放到和索引值和自身相等的位置上,如果做不到就说明有重复; 空间复杂度O(1)

  • 把numbers[i]放到和自身值相等的索引处, 比如numbers[i]=2,就把numbers[i]赋给numbers[2]
  • 核心:如果0,…,n-1这n个数没有重复,这n个数可以放在和自身值相等的索引处, 比如1在索引1处,2在索引2处,n-1在索引n-1处
public class Solution {
public boolean duplicate(int numbers[],int length,int [] duplication) {
if(numbers==null || length < 2)
return false;
/*
核心:如果0,...,n-1这n个数没有重复,这n个数可以放在和自身值相等的索引处, 比如1在索引1处,2在索引2处,n-1在索引n-1处
*/
for(int i=0; i<length; i++){
//它在它应该在的位置上
if(numbers[i] == i)
continue;
//它不在它应该在的位置上 && 它应该在的位置上的值等于它(说明它重复了)
if(numbers[numbers[i]] == numbers[i]){
duplication[0] = numbers[i];
return true;
}
//它不在它应该在的位置上 && 它应该在的位置上得值不等于它(把它放到它应该在的位置上)
int temp = numbers[numbers[i]];
numbers[numbers[i]] = numbers[i];
numbers[i] = temp;
}
return false;
}
}

第二次做, 使用哈希的思想,创建一个辅助数组, 空间复杂度O(N); 循环中涉及执行顺序的问题:先++再if; 我开始弄反了,因为误以为如果当前数出现了2次后直接if判断,而不用++后再判断,但是这是错的; 因为一个数出现2次应该在当次循环中就进行判断, 而不是在下一次循环中进行判断; 还得意识到arr[numbers[i]]从0开始

public class Solution {
public boolean duplicate(int numbers[],int length,int [] duplication) {
if(numbers==null || length<2)
return false;
int[] arr = new int[length];
for(int i=0; i<length; i++){
arr[numbers[i]]++;
if(arr[numbers[i]] == 2){
duplication[0] = numbers[i];
return true;
}
}
return false;
}
}
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(length <= 0)
return false;
for(int i = 0; i<length; i++){
if(numbers[i] > length - 1 || numbers[i] < 0)
return false;
}
// 正式判断, 逐个位置处理
for(int i = 0 ; i < length; i++){
while(numbers[i] != i){ // 直到把索引i的位置处理正确后才调出循环
int m = numbers[i];
if(m == numbers[m]){
duplication[0] = m;
return true;
}
// swap
int temp = numbers[i];
numbers[i] = numbers[m];
numbers[m] = temp;
}
}
return false;
}
}