版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/littlehaes/article/details/91382664
welcome to my blog
面试题3_数组中重复的数字
思路
- 逐个位置判断, 对于当前位置, 要么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)
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;
}
}