Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
其实这个题我以前做过类似的,基于HashSet可以很方便的求解;
代码如下:
public static boolean containsDuplicate(int[] nums){
if (nums.length==0||nums.length==1) {
return false;
}
HashSet<Integer> hashSet = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if(hashSet.add(nums[i])==false)
return true;
}
return false;
}