java实现
//方法一:稍微快点
class Solution {
public int duplicateInArray(int[] nums) {
if(nums.length==0)return -1;
Arrays.sort(nums);
if(nums[0]<0||nums[nums.length-1]>nums.length-1)
return -1;
for (int i = 0; i < nums.length-1; i++) {
if(nums[i]==nums[i+1]){
return nums[i];
}
}
return -1;
}
}
//方法二:
public static int duplicateInArray(int[] nums) {
Set<Integer>set=new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if(nums[i]<0||nums[i]>nums.length-1)return -1;
}
for (int i = 0; i < nums.length; i++) {
if(set.contains(nums[i]))return nums[i];
set.add(nums[i]);
}
return -1;
}