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.
public class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer,Integer> ans = new HashMap<Integer,Integer>();
boolean flag = false;
for(int num : nums){
if(ans.containsKey(num)){
flag = true;
break;
}else
ans.put(num,1);
}
return flag;
}
}
总结:时间复杂度应该是O(n)。不知道为何只超过4%。