-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDay-2 Design HashSet
More file actions
66 lines (53 loc) · 1.45 KB
/
Day-2 Design HashSet
File metadata and controls
66 lines (53 loc) · 1.45 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
63
64
65
66
class MyHashSet {
private Bucket[] bucketArray;
private int keyRange;
/** Initialize your data structure here. */
public MyHashSet() {
this.keyRange = 769;
this.bucketArray = new Bucket[this.keyRange];
for (int i = 0; i < this.keyRange; ++i)
this.bucketArray[i] = new Bucket();
}
protected int _hash(int key) {
return (key % this.keyRange);
}
public void add(int key) {
int bucketIndex = this._hash(key);
this.bucketArray[bucketIndex].insert(key);
}
public void remove(int key) {
int bucketIndex = this._hash(key);
this.bucketArray[bucketIndex].delete(key);
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
int bucketIndex = this._hash(key);
return this.bucketArray[bucketIndex].exists(key);
}
}
class Bucket {
private LinkedList<Integer> container;
public Bucket() {
container = new LinkedList<Integer>();
}
public void insert(Integer key) {
int index = this.container.indexOf(key);
if (index == -1) {
this.container.addFirst(key);
}
}
public void delete(Integer key) {
this.container.remove(key);
}
public boolean exists(Integer key) {
int index = this.container.indexOf(key);
return (index != -1);
}
}
/**
* 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);
*/