705. Design HashSet

class MyHashSet {
    Integer[] set;
    /** Initialize your data structure here. */
    public MyHashSet() {
        this.set = new Integer[1000000]; //int[] cannot assign null value
    }

    public void add(int key) {
        int index = computeHash(key);
        if (!contains(key)) {
            this.set[index] = key;
        }
    }

    public void remove(int key) {
        int index = computeHash(key);
        if (contains(key)) {
            this.set[index] = null;
        }
    }

    /** Returns true if this set contains the specified element */
    public boolean contains(int key) {
        int index = computeHash(key);
        if (this.set[index] != null) {
            return true;
        } else {
            return false;
        } 
    }

    public int computeHash(int key) {
        return key % this.set.length;
    }
}

results matching ""

    No results matching ""