-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashSet.java
More file actions
62 lines (53 loc) · 1.48 KB
/
MyHashSet.java
File metadata and controls
62 lines (53 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class MyHashSet {
private List<Integer>[] buckets;
private int cap = 256;
/** Initialize your data structure here. */
public MyHashSet() {
buckets = new List[cap];
}
public void add(int key) {
if (!contains(key)) {
getBucket(key, buckets).add(key);
}
}
public void remove(int key) {
List<Integer> bucket = getBucket(key, buckets);
ListIterator<Integer> iter = bucket.listIterator();
while (iter.hasNext()) {
if (iter.next() == key) {
iter.remove();
return;
}
}
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
List<Integer> bucket = getBucket(key, buckets);
for (int k: bucket) {
if (k == key) {
return true;
}
}
return false;
}
private List<Integer> getBucket(int key, List<Integer>[] buckets) {
int idx = hash(key);
if (buckets[idx] == null) {
buckets[idx] = new LinkedList<>();
}
return buckets[idx];
}
private int hash(int key) {
return Math.abs(key % cap);
}
}
/**
* 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);
*/