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.
Solution:
Can use hashmap to count frequence of each element.
O(n)
public boolean containsDuplicate(int[] nums) {
int len = nums.length;
if(len <= 1) return false;
Map<Integer, Integer> count = new HashMap<>();
for(int i = 0;i < len; i++) {
if(count.containsKey(nums[i])) {
if(count.get(nums[i]) == 1) return true;
}
count.put(nums[i], 1);
}
return false;
}