Check if a Java array Contains Duplicates
The challenge
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.
Example 1:
Example 2:
Example 3:
The solution
class Solution {
// return a boolean from the primitive int array input
public boolean containsDuplicate(int[] nums) {
// create a HashMap to hold our values
HashMap<Integer, Integer> hm = new HashMap<>();
// loop through the input array
for (int i=0; i<nums.length; i++) {
// return true if we have seen a duplicate
// otherwise add the int to the HashMap
if (hm.get(nums[i])!=null) return true;
else hm.put(nums[i], 1);
}
// return false if all else fails
return false;
}
}