forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyHashSet.java
61 lines (49 loc) · 1.56 KB
/
MyHashSet.java
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
// Time Complexity : O(1) for all operations
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None
// Your code here along with comments explaining your approach
class MyHashSet {
private boolean[][] storage;
private int buckets;
private int bucketItems;
public MyHashSet() {
this.buckets = 1000;
this.bucketItems = 1000;
this.storage = new boolean[buckets][];
}
private int firstHashFunction(int key) {
return key % this.buckets;
}
private int secondHashFunction(int key) {
return key / this.bucketItems;
}
public void add(int key) {
int bucket = firstHashFunction(key);
int bucketItem = secondHashFunction(key);
if (storage[bucket] == null) {
if (bucket == 0) {
storage[bucket] = new boolean[bucketItems + 1];
} else {
storage[bucket] = new boolean[bucketItems];
}
}
storage[bucket][bucketItem] = true;
}
public void remove(int key) {
int bucket = firstHashFunction(key);
int bucketItem = secondHashFunction(key);
if (storage[bucket] == null) {
return;
}
storage[bucket][bucketItem] = false;
}
public boolean contains(int key) {
int bucket = firstHashFunction(key);
int bucketItem = secondHashFunction(key);
if (storage[bucket] == null) {
return false;
}
return storage[bucket][bucketItem];
}
}