Buckets with chaining
Time O(1) average per call Space O(n + buckets)An array of 1009 lists (a prime spreads keys well). add appends if absent, remove deletes, contains searches one bucket.
import java.util.*;
class MyHashSet {
private static final int BUCKETS = 1009;
private final List<List<Integer>> table = new ArrayList<>();
public MyHashSet() {
for (int i = 0; i < BUCKETS; i++) table.add(new LinkedList<>());
}
private List<Integer> bucket(int key) { return table.get(key % BUCKETS); }
public void add(int key) {
if (!bucket(key).contains(key)) bucket(key).add(key);
}
public void remove(int key) {
bucket(key).remove(Integer.valueOf(key)); // remove the value, not the index
}
public boolean contains(int key) { return bucket(key).contains(key); }
}Verdict: This is how real hash sets work (plus resizing).