-
Notifications
You must be signed in to change notification settings - Fork 0
/
DesignHashSet.java
107 lines (87 loc) · 2.55 KB
/
DesignHashSet.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
public class DesignHashSet {
/**
* Solutiion using boolean[]
*/
class MyHashSet {
// Array to store presence of key in HashSet
private boolean[] isKeyPresent;
/**
* Initialize your data structure here.
*/
public MyHashSet() {
// key is [0, 1000000]
this.isKeyPresent = new boolean[1000001];
}
public void add(int key) {
isKeyPresent[key] = true;
}
public void remove(int key) {
isKeyPresent[key] = false;
}
/**
* Returns true if this set contains the specified element
*/
public boolean contains(int key) {
return isKeyPresent[key];
}
}
/**
* 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);
*/
/**
* Solution using Linked List (chaining)
*/
class MyHashSet {
private Bucket[] buckets;
private int keyRange;
/**
* Initialize your data structure here.
*/
public MyHashSet() {
this.keyRange = 769;
this.buckets = new Bucket[this.keyRange];
for (int i = 0; i < this.keyRange; ++i) {
this.buckets[i] = new Bucket();
}
}
protected int _hash(int key) {
return key % this.keyRange;
}
public void add(int key) {
int bucketIndex = _hash(key);
this.buckets[bucketIndex].insert(key);
}
public void remove(int key) {
int bucketIndex = _hash(key);
this.buckets[bucketIndex].delete(key);
}
/**
* Returns true if this set contains the specified element
*/
public boolean contains(int key) {
int bucketIndex = _hash(key);
return this.buckets[bucketIndex].exists(key);
}
}
class Bucket {
private LinkedList<Integer> container;
public Bucket() {
this.container = new LinkedList<Integer>();
}
public void insert(int key) {
int index = this.container.indexOf(key);
if (index == -1) this.container.addFirst(key);
}
public void delete(int key) {
this.container.remove(key);
}
public boolean exists(int key) {
int index = this.container.indexOf(key);
return index != -1;
}
}
}