forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
51 lines (45 loc) · 1.12 KB
/
Solution2.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
class MyHashSet {
private static final int SIZE = 1000;
private LinkedList[] data;
public MyHashSet() {
data = new LinkedList[SIZE];
for (int i = 0; i < SIZE; ++i) {
data[i] = new LinkedList<Integer>();
}
}
public void add(int key) {
if (contains(key)) {
return;
}
int idx = hash(key);
data[idx].addFirst(key);
}
public void remove(int key) {
if (!contains(key)) {
return;
}
int idx = hash(key);
data[idx].remove(Integer.valueOf(key));
}
public boolean contains(int key) {
int idx = hash(key);
Iterator<Integer> it = data[idx].iterator();
while (it.hasNext()) {
Integer e = it.next();
if (e == key) {
return true;
}
}
return false;
}
private int hash(int key) {
return key % SIZE;
}
}
/**
* 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);
*/