[Solution]217. Contains Duplicate

·

1 min read

Problem

Problem_Link

Solutions (time, space)

O(n), O(n)

class Solution {
    public boolean containsDuplicate(int[] nums) {
        // Create a HashMap to store the elements of the array
        HashMap<Integer, Integer> map = new HashMap<>();

        // Loop through each element of the array
        for (int temp : nums) {
            // Check if the element already exists in the HashMap
            if (map.containsKey(temp)) {
                // If it does, return true as there is a duplicate in the array
                return true;
            } else {
                // If it doesn't, add it to the HashMap with a value of 1
                // 1 does not mean anything it just notices there is duplication
                map.put(temp, 1);
            }
        }
        // Return false if no duplicates were found
        return false;
    }
}

addition

  • using an array or bit manipulation to solve this problem is complicated for teamwork.

  • using HashSet is the same as using a hashmap. HashSet initially calls a dummy hashmap while calling HashSet. HashSet code is a little shorter than hashmap code. I believe that a hashmap is better.

O(n), O(n)

class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> set = new HashSet<>(nums.length);

        for(int temp: nums) {
            if(!set.add(temp)) {
                return true;
            }
        }
        return false;
    }
}