forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesignHashMap.java
More file actions
103 lines (78 loc) · 2.01 KB
/
Copy pathDesignHashMap.java
File metadata and controls
103 lines (78 loc) · 2.01 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
class MyHashMap {
class Node {
int key;
int value;
Node next;
Node(int key, int value) {
this.key = key;
this.value = value;
this.next = null;
}
}
private Node[] storage;
public MyHashMap() {
this.storage = new Node[10000];
}
private int hash(int key) {
return key % 10000;
}
private Node find(Node head, int key) {
Node curr = head;
Node prev = null;
while(curr != null && curr.key != key) {
prev = curr;
curr = curr.next;
}
return prev;
}
public void put(int key, int value) {
int idx = hash(key);
if (storage[idx] == null) {
// initialzie with dummy node
storage[idx] = new Node(-1,-1); // dummy
}
Node prev = find(storage[idx], key);
if(prev.next != null) {
prev.next.value = value;
}
else {
Node newNode = new Node(key,value);
prev.next = newNode;
}
}
public int get(int key) {
int idx = hash(key);
if(storage[idx] == null) {
return -1;
}
else {
Node prev = find(storage[idx],key);
Node curr = prev.next;
while (curr != null) {
if(curr.key == key) {
return curr.value;
}
curr = curr.next;
}
return -1;
}
}
public void remove(int key) {
int idx = hash(key);
if(storage[idx] == null) {
return ;
}
Node prev = find(storage[idx], key);
if(prev.next == null) {
return ;
}
prev.next = prev.next.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);
*/