-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesignHashSet.java
More file actions
86 lines (75 loc) · 1.93 KB
/
Copy pathDesignHashSet.java
File metadata and controls
86 lines (75 loc) · 1.93 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class MyHashSet {
private static class LinkedList {
static class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
private final Node dummy = new Node(0);
void add(int x) {
Node p = dummy.next;
while (p != null) {
if (p.val == x) break;
else p = p.next;
}
if (p == null) {
Node node = new Node(x);
node.next = dummy.next;
dummy.next = node;
}
}
void remove(int x) {
Node p = dummy;
while (p.next != null) {
if (p.next.val == x) {
p.next = p.next.next;
return;
}
p = p.next;
}
}
boolean contains(int x) {
Node p = dummy.next;
while(p != null) {
if(p.val == x) return true;
p = p.next;
}
return false;
}
}
private final LinkedList[] data;
private final static int N = 10;
/**
* Initialize your data structure here.
*/
public MyHashSet() {
data = new LinkedList[N];
for (int i = 0; i < N; i++) {
data[i] = new LinkedList();
}
}
public void add(int key) {
int ind = key % N;
data[ind].add(key);
}
public void remove(int key) {
int ind = key % N;
data[ind].remove(key);
}
/**
* Returns true if this set contains the specified element
*/
public boolean contains(int key) {
int ind = key % N;
return data[ind].contains(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);
*/