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.
先排序,然后判断。Accept。
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1])
return true;
}
return false;
}
我想着用List或者Set装着,然后判断在不在里面。但是全都超时了。
public boolean containsDuplicate1(int[] nums) {
Set<Integer> unique = new HashSet<Integer>();
for (int x : nums) {
if (unique.contains(x))
return true;
else
unique.add(x);
}
return false;
}
public boolean containsDuplicate(int[] nums) {
if (nums.length == 0)
return false;
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) {
if (list.contains(nums[i]))
return true;
else
list.add(nums[i]);
}
return false;
}