-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashMap.java
More file actions
58 lines (50 loc) · 1.39 KB
/
Copy pathMyHashMap.java
File metadata and controls
58 lines (50 loc) · 1.39 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
import java.util.ArrayList;
import java.util.List;
class MyHashMap {
private int maxBucket = 10001;
private List<List<int[]>> bucket;
public MyHashMap() {
bucket = new ArrayList<>(maxBucket);
for(int i=0;i<maxBucket;i++){
bucket.add(new ArrayList<>());
}
}
public void put(int key, int value) {
int idx = key%maxBucket;
List<int[]> keyValuePairList = bucket.get(idx);
for (int[] pair : keyValuePairList) {
if (pair[0] == key) {
pair[1] = value;
return;
}
}
keyValuePairList.add(new int[]{key,value});
}
public int get(int key) {
int idx = key % maxBucket;
List<int[]> keyValuePairList = bucket.get(idx);
for (int[] pair : keyValuePairList) {
if (pair[0] == key) {
return pair[1];
}
}
return -1;
}
public void remove(int key) {
int idx = key % maxBucket;
List<int[]> keyValuePairList = bucket.get(idx);
for (int[] pair : keyValuePairList) {
if (pair[0] == key) {
pair[1] = -1;
return;
}
}
}
}
/**
* 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);
*/