Given an array of integers,find if the array contains any duplicates. Your function should return true ifany value appears at least twice in the array, and it should return false ifevery element is distinct.
翻译:给定一个整数数组,找到该数组是否包含任何重复。如果任何一个值在数组中至少出现两次,则函数应返回true,如果每个元素都不同,则函数应返回false。
题目不是很好写,想了很多方法,发现都超时了,也不知道为什么。最后看了一下参考答案,发现别人用的HashSet,难道它的contains查找比ArrayList的快,发现他们都是重写AbstractCollection。最后想想可能是存储速度,发现可能是这个原因。HashSet中有一个HashMap类的成员,所以我使用这两个类都通过测试了的。具体代码如下:
public class Solution {
public boolean containsDuplicate(int[]nums) {
/* Set<Integer> set = newHashSet<Integer>();
for(int i=0;i<nums.length;i++){
if(set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
}
return false;*/
Map<Integer,Integer> ls = newHashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(ls.containsKey(nums[i])){
return true;
}
ls.put(nums[i],i);
}
return false;
/*List<Integer> ls=newArrayList();
for(int i=0;i<nums.length;i++){
if(ls.contains(nums[i])){
return true;
}else{
ls.add(nums[i]);
}
}
return false;*/
}
}