forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashMap.java
More file actions
51 lines (45 loc) · 1.45 KB
/
MyHashMap.java
File metadata and controls
51 lines (45 loc) · 1.45 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
class MyHashMap {
int primaryBuckets;
int secondaryBuckets;
int[][] storage;
public MyHashMap() {
this.primaryBuckets = 1000;
this.secondaryBuckets = 1000;
this.storage = new int[primaryBuckets][];
}
private int getPrimaryHash(int key){
return key % primaryBuckets;
}
private int getSecondaryHash(int key){
return key / secondaryBuckets;
}
public void put(int key, int value) {
int primaryIndex = getPrimaryHash(key);
if(storage[primaryIndex] == null){
if(primaryIndex == 0){
storage[primaryIndex] = new int[secondaryBuckets+1];
}else{
storage[primaryIndex] = new int[secondaryBuckets];
}
Arrays.fill(storage[primaryIndex], -1);
}
int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = value;
}
public void remove(int key) {
int primaryIndex = getPrimaryHash(key);
if(storage[primaryIndex] == null){
return;
}
int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = -1;
}
public int get(int key) {
int primaryIndex = getPrimaryHash(key);
if(storage[primaryIndex] == null){
return -1;
}
int secondaryIndex = getSecondaryHash(key);
return storage[primaryIndex][secondaryIndex];
}
}