-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashSet.java
More file actions
73 lines (61 loc) · 1.85 KB
/
Copy pathMyHashSet.java
File metadata and controls
73 lines (61 loc) · 1.85 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
package DSA;
import java.util.ArrayList;
import java.util.List;
class MyHashSet {
private int maxBucket = 10001;
private List<List<int[]>> bucket;
public MyHashSet() {
bucket = new ArrayList<>(maxBucket);
for (int i = 0; i < maxBucket; i++) {
bucket.add(new ArrayList<>());
}
}
public void add(int key) {
int idx = key % maxBucket;
List<int[]> keyList = bucket.get(idx);
for (int[] key1 : keyList) {
if (key1[0] == key) {
if (key1[1] > 0) {
return;
} else if (key1[1] < 0) {
key1[1] = 1;
return;
}
}
}
keyList.add(new int[] { key, 1 });
}
public void remove(int key) {
int idx = key % maxBucket;
List<int[]> keyList = bucket.get(idx);
for (int[] key1 : keyList) {
if (key1[0] == key) {
key1[1] = -1;
return;
}
}
}
public boolean contains(int key) {
int idx = key % maxBucket;
List<int[]> keyList = bucket.get(idx);
for (int[] key1 : keyList) {
if (key1[0] == key) {
return key1[1] > 0;
}
}
return false;
}
public static void main(String[] args) {
MyHashSet obj = new MyHashSet();
obj.add(1);
obj.add(2);
System.out.println(obj.contains(1)); // return True
System.out.println(obj.contains(3)); // return False, (not found)
obj.add(2); // set = [1, 2]
System.out.println(obj.contains(2)); // return True
obj.remove(2); // set = [1]
System.out.println(obj.contains(2)); // return False, (already removed)
obj.add(2); // set = [1,2]
System.out.println(obj.contains(2));
}
}