-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathMyHashSet.java
More file actions
60 lines (52 loc) · 1.73 KB
/
MyHashSet.java
File metadata and controls
60 lines (52 loc) · 1.73 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)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Approach:
// Use two-level hashing with primary and secondary buckets.
// Map each key to a unique index in a 2D boolean array.
// Lazily initialize buckets to save memory.
class MyHashSet {
int primaryBuckets;
int secondaryBuckets;
boolean[][] storage;
public MyHashSet() {
this.primaryBuckets = 1000;
this.secondaryBuckets = 1000;
this.storage = new boolean[primaryBuckets][];
}
private int getPrimaryHash(int key){
return key % primaryBuckets;
}
private 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];
}
}