-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathDesign HashMap.java
More file actions
46 lines (35 loc) · 1.17 KB
/
Design HashMap.java
File metadata and controls
46 lines (35 loc) · 1.17 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
class MyHashMap {
private static final int BUCKET_COUNT = 1001;
private static final int BUCKET_SIZE = 1001;
private final Integer[][] map;
public MyHashMap() {
this.map = new Integer[BUCKET_COUNT][BUCKET_SIZE];
}
public void put(int key, int value) {
Position position = getPosition(key);
map[position.bucket()][position.index()] = value;
}
public int get(int key) {
Position position = getPosition(key);
Integer value = map[position.bucket()][position.index()];
return value == null ? -1 : value;
}
public void remove(int key) {
Position position = getPosition(key);
map[position.bucket()][position.index()] = null;
}
private static Position getPosition(int key) {
int bucket = key / BUCKET_COUNT;
int index = key % BUCKET_SIZE;
return new Position(bucket, index);
}
private static record Position(int bucket, int index) {
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/