forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0706-design-hashmap.java
44 lines (44 loc) · 1.18 KB
/
0706-design-hashmap.java
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
class ListNode {
int key, val;
ListNode next;
public ListNode(int key, int val, ListNode next) {
this.key = key;
this.val = val;
this.next = next;
}
}
class MyHashMap {
static final int size = 19997;
static final int mult = 12582917;
ListNode[] data;
public MyHashMap() {
this.data = new ListNode[size];
}
private int hash(int key) {
return (int)((long)key * mult % size);
}
public void put(int key, int val) {
remove(key);
int h = hash(key);
ListNode node = new ListNode(key, val, data[h]);
data[h] = node;
}
public int get(int key) {
int h = hash(key);
ListNode node = data[h];
for (; node != null; node = node.next)
if (node.key == key) return node.val;
return -1;
}
public void remove(int key) {
int h = hash(key);
ListNode node = data[h];
if (node == null) return;
if (node.key == key) data[h] = node.next;
else for (; node.next != null; node = node.next)
if (node.next.key == key) {
node.next = node.next.next;
return;
}
}
}