-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesignHashSet.java
More file actions
92 lines (82 loc) · 2.13 KB
/
DesignHashSet.java
File metadata and controls
92 lines (82 loc) · 2.13 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
87
88
89
90
91
92
package easy;
/**
* ClassName: DesignHashSet.java
* Author: chenyiAlone
* Create Time: 2019/12/12 8:28
* Description: No.705 Design HashSet
*/
public class DesignHashSet {
private class Node {
Node next;
int key;
Node() {}
Node(int key) {
this.key = key;
}
}
private Node[] buckets;
private int size;
private int len = 64;
/** Initialize your data structure here. */
public DesignHashSet() {
buckets = new Node[len];
size = 0;
}
public void add(int key) {
int pos = key & (len - 1);
if (buckets[pos] == null) {
buckets[pos] = new Node(key);
} else {
Node n = buckets[pos];
while (n != null && n.key != key)
n = n.next;
if (n != null)
return;
else {
Node ins = new Node(key);
ins.next = buckets[pos];
buckets[pos] = ins;
}
}
size++;
}
public void remove(int key) {
int pos = key & (len - 1);
if (buckets[pos] == null)
return;
Node prev = null, cur = buckets[pos];
while (cur != null && cur.key != key) {
prev = cur;
cur = cur.next;
}
if (cur == null) return;
if (prev == null) {
buckets[pos] = buckets[pos].next;
} else {
prev.next = cur.next;
}
size--;
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
int pos = key & (len - 1);
if (buckets[pos] == null)
return false;
Node prev = null, cur = buckets[pos];
while (cur != null && cur.key != key) {
prev = cur;
cur = cur.next;
}
if (cur != null)
return true;
else
return false;
}
}
/**
* 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);
*/