forked from super30admin/Design-1
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHashMap.java
More file actions
Latest commit
74 lines (64 loc) · 1.67 KB
/
Copy pathMyHashMap.java
File metadata and controls
74 lines (64 loc) · 1.67 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
//Design a Hash Map
//Time Complexity : Amortized O(1)
//Space Complexity : O(n)
classMyHashMap {
Node[] map;
intbuckets;
privatestaticclassNode {
intkey;
intval;
Nodenext;
publicNode(intkey, intval) {
this.key = key;
this.val = val;
}
}
publicMyHashMap() {
this.buckets = 1000;
map = newNode[buckets];
}
privateNodegetPrevious(Nodehead, intkey) {
Nodeprev = null;
Nodecurr = head;
while(curr != null && curr.key != key) {
prev = curr;
curr = curr.next;
}
returnprev;
}
publicvoidput(intkey, intvalue) {
Nodecurr = newNode(key, value);
intindex = key % buckets;
if(map[index] == null) {
map[index] = newNode(-1,-1);
map[index].next = curr;
}
else {
Nodeprev = getPrevious(map[index], key);
if(prev.next == null) {
prev.next = curr;
} else {
prev.next.val = value;
}
}
}
publicintget(intkey) {
intindex = key % buckets;
if(map[index] == null)
return -1;
Nodeprev = getPrevious(map[index], key);
if(prev.next == null)
return -1;
returnprev.next.val;
}
publicvoidremove(intkey) {
intindex = key % buckets;
if(map[index] == null)
return;
Nodeprev = getPrevious(map[index], key);
if(prev.next == null) return;
Nodetemp = prev.next;
prev.next = temp.next;
temp.next = null;
}
}