-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path7. Design HashMap
90 lines (77 loc) · 2.09 KB
/
7. Design HashMap
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
class MyHashMap {
private int[] hash;
/** Initialize your data structure here. */
public MyHashMap() {
hash = new int[100001];
}
/** value will always be non-negative. */
public void put(int key, int value) {
hash[key] = value + 1;
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
return hash[key] - 1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
hash[key] = 0;
}
}
class MyHashMap {
/** Initialize your data structure here. */
LinkedList<Entry>[] map;
public static int SIZE = 769;
public MyHashMap() {
map = new LinkedList[SIZE];
}
/** value will always be non-negative. */
public void put(int key, int value) {
int bucket = key % SIZE;
if(map[bucket] == null) {
map[bucket] = new LinkedList<Entry>();
map[bucket].add(new Entry(key, value));
}
else {
for(Entry entry : map[bucket]){
if(entry.key == key){
entry.val = value;
return;
}
}
map[bucket].add(new Entry(key, value));
}
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
int bucket = key % SIZE;
LinkedList<Entry> entries = map[bucket];
if(entries == null) return -1;
for(Entry entry : entries) {
if(entry.key == key) return entry.val;
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
int bucket = key % SIZE;
Entry toRemove = null;
if(map[bucket] == null) return;
else {
for(Entry entry : map[bucket]){
if(entry.key == key) {
toRemove = entry;
}
}
if(toRemove == null) return;
map[bucket].remove(toRemove);
}
}
}
class Entry {
public int key;
public int val;
public Entry(int key, int val){
this.key = key;
this.val = val;
}
}