forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashSet.java
More file actions
58 lines (47 loc) · 1.55 KB
/
Copy pathMyHashSet.java
File metadata and controls
58 lines (47 loc) · 1.55 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
// Time Complexity : O(1) for all operations
// Space Complexity : O(n) where n is the number of elements in the hashset
// Did this code successfully run on Leetcode : Yes
class MyHashSet {
int primaryBucketSize = 1000;
int secondaryBucketSize = 1001;
public boolean[][] storage;
public MyHashSet() {
storage = new boolean[primaryBucketSize][];
}
public int getPrimaryHash(int key) {
return key / secondaryBucketSize;
}
public int getSecondaryHash(int key) {
return key % secondaryBucketSize;
}
public void add(int key) {
int primaryHash = getPrimaryHash(key);
int secondaryHash = getSecondaryHash(key);
if(storage[primaryHash] == null) {
storage[primaryHash] = new boolean[secondaryBucketSize];
}
storage[primaryHash][secondaryHash] = true;
}
public void remove(int key) {
int primaryHash = getPrimaryHash(key);
int secondaryHash = getSecondaryHash(key);
if (storage[primaryHash] != null) {
storage[primaryHash][secondaryHash] = false;
}
}
public boolean contains(int key) {
int primaryHash = getPrimaryHash(key);
int secondaryHash = getSecondaryHash(key);
if (storage[primaryHash] == null) {
return false;
}
return storage[primaryHash][secondaryHash];
}
}
/**
* 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);
*/