问题描述:找出一个数组中是否有重复出现的数字。
思路:两种实现方式:1、通过map。2、排序,然后比较数字。后一种运行时间较好。
原答案:
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
int length=nums.length-1;
for(int i=0;i<length;i++){
if(nums[i]==nums[i+1])
return true;
}
return false;
}
最佳答案:
public boolean containsDuplicate(int[] nums) {
//当数组不存在,或者长度小于2时,不可能存在重复数据
if(nums == null || nums.length <= 1 ){
return false;
}
//找出数组中的最大数和最小数
int min = nums[0];
int max = nums[0];
for(int i = 1, size = nums.length; i < size; i++){
if(nums[i] < min){
min = nums[i];
}else if(nums[i] > max){
max = nums[i];
}
}
//若最大最小数的区间小于数组长度,必定存在重复数据
if((max - min + 1 ) < nums.length){
return true;
}
boolean[] results = new boolean[max - min + 1];
for(int i = 0,size = nums.length; i < size; i++){
//减去最小数,保证偏移量为整数
int index = nums[i] - min;
//若boolean数组该位置被置为true,表示该数已经出现过
if(results[index]){
return true;
}
//将boolean该偏移位置设置为true
results[index] = true;
}
return false;
}
强行找出数组的上下界构建记录数组,虽然这个想法也想到了,但是如果上下界差值远远大于数组中数据个数时,表现应该就不那么好了。