forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSet.java
More file actions
60 lines (52 loc) · 1.87 KB
/
HashSet.java
File metadata and controls
60 lines (52 loc) · 1.87 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
// Time Complexity : O(1) for add (amortized), remove and contains
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this :
// this approach uses double hashing to store the keys in a 2D boolean array.
// The primary hash function determines the index of the first dimension,
// while the secondary hash function determines the index of the second dimension.
// This allows us to efficiently store and retrieve keys while minimizing space usage.
class MyHashSet {
int primaryBuckets;
int secondaryBuckets;
boolean[][] storage;
public MyHashSet() {
primaryBuckets = 1000;
secondaryBuckets = 1000;
storage = new boolean[primaryBuckets][];
}
int getPrimaryHash(int key){
return key%primaryBuckets;
}
int getSecondaryHash(int key){
return key/secondaryBuckets;
}
public void add(int key) {
int primaryIndex = getPrimaryHash(key);
if(storage[primaryIndex]==null){
if(primaryIndex == 0){
storage[primaryIndex] = new boolean[secondaryBuckets +1];
}else{
storage[primaryIndex] = new boolean[secondaryBuckets];
}
}
int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = true;
}
public void remove(int key) {
int primaryIndex = getPrimaryHash(key);
if(storage[primaryIndex]==null){
return;
}
int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = false;
}
public boolean contains(int key) {
int primaryIndex = getPrimaryHash(key);
if(storage[primaryIndex]==null){
return false;
}
int secondaryIndex = getSecondaryHash(key);
return storage[primaryIndex][secondaryIndex];
}
}