Design HashMap LeetCode solution in Java

1
class MyHashMap {
2

3
/** Initialize your data structure here. */
4
LinkedList<Entry>[] map;
5

6
public static int SIZE = 769;
7

8
public MyHashMap() {
9
map = new LinkedList[SIZE];
10
}
11

12
/** value will always be non-negative. */
13
public void put(int key, int value) {
14
int bucket = key % SIZE;
15
if (map[bucket] == null) {
16
map[bucket] = new LinkedList<Entry>();
17
map[bucket].add(new Entry(key, value));
18
} else {
19
for (Entry entry : map[bucket]) {
20
if (entry.key == key) {
21
entry.val = value;
22
return;
23
}
24
}
25
map[bucket].add(new Entry(key, value));
26
}
27
}
28

29
/**
30
* Returns the value to which the specified key is mapped, or -1 if this map contains no mapping
31
* for the key
32
*/
33
public int get(int key) {
34
int bucket = key % SIZE;
35
LinkedList<Entry> entries = map[bucket];
36
if (entries == null) return -1;
37
for (Entry entry : entries) {
38
if (entry.key == key) return entry.val;
39
}
40
return -1;
41
}
42

43
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
44
public void remove(int key) {
45
int bucket = key % SIZE;
46
Entry toRemove = null;
47
if (map[bucket] == null) return;
48
else {
49
for (Entry entry : map[bucket]) {
50
if (entry.key == key) {
51
toRemove = entry;
52
}
53
}
54
if (toRemove == null) return;
55
map[bucket].remove(toRemove);
56
}
57
}
58
}
59

60
class Entry {
61
public int key;
62
public int val;
63

64
public Entry(int key, int val) {
65
this.key = key;
66
this.val = val;
67
}
68
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0