forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSet1.java
More file actions
59 lines (49 loc) · 1.34 KB
/
Copy pathHashSet1.java
File metadata and controls
59 lines (49 loc) · 1.34 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
/**
* Using boolean array matrix as Jaspinder explained in the class
* Using 2 hashing algos, and initiating secondary array only if required.
* Time Complexity : O(1)
* Space Complexity : O(N)
* Did this code successfully run on Leetcode : Yes
*/
class MyHashSet {
boolean[][] buckets;
int n = 1001;
public MyHashSet() {
buckets = new boolean[n][];
}
public void add(int key) {
int firstKeyHash = firstHash(key);
int secondKeyHash = secondHash(key);
if(buckets[firstKeyHash] == null){
buckets[firstKeyHash] = new boolean[n];
}
buckets[firstKeyHash][secondKeyHash] = true;
}
public void remove(int key) {
int firstKeyHash = firstHash(key);
int secondKeyHash = secondHash(key);
if(buckets[firstKeyHash] == null){
return;
}
else{
buckets[firstKeyHash][secondKeyHash] = false;
}
}
public boolean contains(int key) {
int firstKeyHash = firstHash(key);
int secondKeyHash = secondHash(key);
if(buckets[firstKeyHash] == null){
return false;
}
else if(buckets[firstKeyHash][secondKeyHash] == true){
return true;
}
return false;
}
public int firstHash(int num){
return num % n;
}
public int secondHash(int num){
return num / n;
}
}