forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesignHashSet.java
More file actions
73 lines (63 loc) · 1.84 KB
/
DesignHashSet.java
File metadata and controls
73 lines (63 loc) · 1.84 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
61
62
63
64
65
66
67
68
69
70
71
72
73
// Time Complexity : O(1)
// Space Complexity : O(N)
// Did this code successfully run on Leetcode : yes, Runtime 12 ms; Beats - 98.30%
// Any problem you faced while coding this : yes - i forogt that i could access a 2-d array as set[primaryBucket], no need to access as set[primaryBucket][]
// Your code here along with comments explaining your approach
class MyHashSet {
int buckets;
int bucketSize;
boolean [][] set;
public MyHashSet() {
this.buckets = 1000;
this.bucketSize = 1000;
set = new boolean[1000][];
}
private int hash1(int key)
{
return key%buckets;
}
private int hash2(int key)
{
return key/bucketSize;
}
public void add(int key) {
int primaryBucket = hash1(key);
if(set[primaryBucket] == null)
{
if(0 == primaryBucket)
{
set[primaryBucket] = new boolean[bucketSize+1];
}
else
{
set[primaryBucket] = new boolean[bucketSize];
}
}
int secondaryBucket = hash2(key);
set[primaryBucket][secondaryBucket] = true;
}
public void remove(int key) {
int primaryBucket = hash1(key);
if(null != set[primaryBucket])
{
int secondaryBucket = hash2(key);
set[primaryBucket][secondaryBucket] = false;
}
}
public boolean contains(int key) {
int primaryBucket = hash1(key);
if(null != set[primaryBucket])
{
int secondaryBucket = hash2(key);
return set[primaryBucket][secondaryBucket];
}
return false;
}
}
/**
* 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);
*/