705 Design HashSet

12 阅读1分钟

image.png

class MyHashSet {
    
    private LinkedList[] buckets;
    private static final int BASE = 769;

    public MyHashSet() {
        buckets = new LinkedList[BASE];
        for (int i = 0; i < BASE; i++) {
            buckets[i] = new LinkedList<Integer>();
        }
    }

    private int hash(int key) {
        return key % BASE;
    }
    
    public void add(int key) {
        int h = hash(key);
        Iterator<Integer> it = buckets[h].iterator();
        while (it.hasNext()) {
            int k = it.next();
            if (k == key) {
                return;
            }
        }
        buckets[h].offer(key);
    }
    
    public void remove(int key) {
        int h = hash(key);
        Iterator<Integer> it = buckets[h].iterator();
        while (it.hasNext()) {
            Integer k = it.next(); //. !!
            if (k == key) {
                buckets[h].remove(k);
                return;
            }
        }
        
    }
    
    public boolean contains(int key) {
        int h = hash(key);
        Iterator<Integer> it = buckets[h].iterator();
        while (it.hasNext()) {
            int k = it.next();
            if (k == key) {
                return true;
            }
        }
        return false;
    }
}

/**
 * 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);
 */