Design HashSet

Design a HashSet without using any built-in hash table libraries.

To be specific, your design should include these functions:


Example:

MyHashSet hashSet = new MyHashSet();
hashSet.add(1);         
hashSet.add(2);         
hashSet.contains(1);    // returns true
hashSet.contains(3);    // returns false (not found)
hashSet.add(2);          
hashSet.contains(2);    // returns true
hashSet.remove(2);          
hashSet.contains(2);    // returns false (already removed)


Note:


Solution:

class MyHashSet {

    List<Integer>[] set;
    /** Initialize your data structure here. */
    public MyHashSet() {
        set = new List[10000]; 
    }
    
    public void add(int key) {
        int k = key % 10000;
        if (set[k] == null) {
            set[k] = new ArrayList();
        }
        set[k].add(key);
    }
    
    public void remove(int key) {
        int k = key % 10000;
        if (set[k] == null) return;
        set[k].removeIf(Integer.valueOf(key)::equals);
    }
    
    /** Returns true if this set contains the specified element */
    public boolean contains(int key) {
        int k = key % 10000;
        if (set[k] == null) return false;
        return set[k].contains(key);
    }
}

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet obj = new MyHashSet();
 * obj.add(key);
 * obj.remove(key);
 * boolean param_3 = obj.contains(key);
 */