Use array of buckets with simple modulo hash function.
key % size1class MyHashSet {
2 private List<Integer>[] buckets;
3 private int size = 1000;
4
5 public MyHashSet() {
6 buckets = new List[size];
7 for (int i = 0; i < size; i++) {
8 buckets[i] = new ArrayList<>();
9 }
10 }
11
12 private int hash(int key) {
13 return key % size;
14 }
15
16 public void add(int key) {
17 int idx = hash(key);
18 if (!buckets[idx].contains(key)) {
19 buckets[idx].add(key);
20 }
21 }
22
23 public void remove(int key) {
24 int idx = hash(key);
25 buckets[idx].remove(Integer.valueOf(key));
26 }
27
28 public boolean contains(int key) {
29 int idx = hash(key);
30 return buckets[idx].contains(key);
31 }
32}