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.
这里先用的数组,后来用的是TreeSet,又换成了HashTable都是时间超时,直到换成了HashMap,通过了,代码如下:
public class Solution {
public boolean containsDuplicate(int[] nums) {
HashMap<Integer,Integer> hashMap=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(hashMap.containsKey(nums[i])){
return true;
}
else hashMap.put(nums[i], nums[i]);
}
return false;
}
}