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
79 lines (73 loc) · 1.7 KB
/
MyHashmap.java
File metadata and controls
79 lines (73 loc) · 1.7 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
73
74
75
76
77
78
79
class MyHashMap {
class Node{
int key;
int val;
Node next;
public Node(int key,int val){
this.key=key;
this.val=val;
}}
Node[] storage;
public MyHashMap() {
this.storage= new Node[10000];
}
private int hash(int key){
return key%storage.length;
}
public Node find(Node node,int key) {
Node curr = node;
Node prev = null;
while (curr != null && curr.key != key) {
prev = curr;
curr = curr.next;
}
return prev;
}
public void put(int key,int val){
int index=hash(key);
if(storage[index]==null){
storage[index]=new Node(-1,-1);
}
Node prev=find(storage[index],key);
if (prev.next==null){
prev.next=new Node(key,val);
}
else{
prev.next.val=val;
}
}
public int get(int key){
int index=hash(key);
if(storage[index]==null){
return -1;
}
Node prev=find(storage[index],key);
if (prev.next==null){
return -1;
}
else{
return prev.next.val;
}
}
public void remove(int key){
int index=hash(key);
if(storage[index]==null){
return ;
}
Node prev=find(storage[index],key);
if (prev.next==null){
return ;
}
else{
prev.next=prev.next.next;
prev=prev.next;
}
}
}
/**
* 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);
*/