forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashSet.java
More file actions
72 lines (56 loc) · 1.65 KB
/
Copy pathMyHashSet.java
File metadata and controls
72 lines (56 loc) · 1.65 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
// Time Complexity : O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
public class MyHashSet {
int MAX = 1000000;
int bucketSize;
int innerBucketSize;
boolean[][] storage;
public MyHashSet() {
this.bucketSize = (int) Math.sqrt(MAX);
this.innerBucketSize = MAX/bucketSize;
this.storage = new boolean[bucketSize][];
}
public int hashIndexForBucket(int key)
{
return key%1000;
}
public int hashIndexForInnerBucket(int key)
{
return key/1000;
}
public void add(int key) {
int bucketIndex = hashIndexForBucket(key);
int innerBucketIndex = hashIndexForInnerBucket(key);
if(storage[bucketIndex] == null)
{
if(bucketIndex == 0)
{
storage[bucketIndex] = new boolean[innerBucketSize+1];
}else {
storage[bucketIndex] = new boolean[innerBucketSize];
}
}
storage[bucketIndex][innerBucketIndex] = true;
}
public void remove(int key) {
int bucketIndex = hashIndexForBucket(key);
int innerBucketIndex = hashIndexForInnerBucket(key);
if(storage[bucketIndex] != null)
{
storage[bucketIndex][innerBucketIndex] = false;
}
}
public boolean contains(int key) {
int bucketIndex = hashIndexForBucket(key);
int innerBucketIndex = hashIndexForInnerBucket(key);
if(storage[bucketIndex] != null)
{
return storage[bucketIndex][innerBucketIndex];
}
return false;
}
public static void main(String args[])
{
}
}