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
74 lines (64 loc) · 1.67 KB
/
MyHashMap.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)
class MyHashMap {
Node[] map;
int buckets;
private static class Node {
int key;
int val;
Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
public MyHashMap() {
this.buckets = 1000;
map = new Node[buckets];
}
private Node getPrevious(Node head, int key) {
Node prev = null;
Node curr = head;
while(curr != null && curr.key != key) {
prev = curr;
curr = curr.next;
}
return prev;
}
public void put(int key, int value) {
Node curr = new Node(key, value);
int index = key % buckets;
if(map[index] == null) {
map[index] = new Node(-1,-1);
map[index].next = curr;
}
else {
Node prev = getPrevious(map[index], key);
if(prev.next == null) {
prev.next = curr;
} else {
prev.next.val = value;
}
}
}
public int get(int key) {
int index = key % buckets;
if(map[index] == null)
return -1;
Node prev = getPrevious(map[index], key);
if(prev.next == null)
return -1;
return prev.next.val;
}
public void remove(int key) {
int index = key % buckets;
if(map[index] == null)
return;
Node prev = getPrevious(map[index], key);
if(prev.next == null) return;
Node temp = prev.next;
prev.next = temp.next;
temp.next = null;
}
}