forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashSet.java
More file actions
45 lines (40 loc) · 1.06 KB
/
MyHashSet.java
File metadata and controls
45 lines (40 loc) · 1.06 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
//Design a Hash Set - Double Hashing Solution
//Time Complexity : O(1)
//Space Complexity : O(n)
public class MyHashSet {
boolean[][] set;
int pbucket;
int sbucket;
public MyHashSet() {
this.pbucket = 1000;
this.sbucket = 1000;
this.set = new boolean[pbucket][];
}
public void add(int key) {
int hash1 = key%pbucket;
if(set[hash1] == null) {
//initiate the array
if(hash1 == 0)
set[hash1] = new boolean[sbucket+1];
else
set[hash1] = new boolean[sbucket];
}
int hash2 = key/sbucket;
set[hash1][hash2] = true;
}
public void remove(int key) {
int hash1 = key%pbucket;
if(set[hash1] != null) {
int hash2 = key/sbucket;
set[hash1][hash2] = false;
}
}
public boolean contains(int key) {
int hash1 = key%pbucket;
if(set[hash1] == null) {
return false;
}
int hash2 = key/sbucket;
return set[hash1][hash2];
}
}