Repository navigation
Expand file tree
/
Copy path706_Design_HashMap.java
More file actions
96 lines (76 loc) · 1.89 KB
/
Copy path706_Design_HashMap.java
File metadata and controls
96 lines (76 loc) · 1.89 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
class MyHashMap {
private class Node {
private int key, value;
public Node(int k, int v) {
key = k;
value = v;
}
}
private Node[] m;
private int size, capacity;
private static final double LOAD_CAPACITY = 0.66;
public MyHashMap() {
size = 0;
capacity = 5000;
m = new Node[capacity];
}
private int getHash(int key) {
return key % capacity;
}
private void resize() {
if (size <= LOAD_CAPACITY * capacity) {
return;
}
size = 0;
capacity *= 2;
Node[] temp = m;
m = new Node[capacity];
for (int i = 0; i < temp.length; i++) {
if (temp[i] == null || temp[i].key == -1) {
continue;
}
put(temp[i].key, temp[i].value);
}
}
public void put(int key, int value) {
int idx = getHash(key);
while (m[idx] != null) {
if (m[idx].key == key) {
m[idx].value = value;
return;
}
++idx;
idx %= capacity;
}
m[idx] = new Node(key, value);
++size;
resize();
}
public int get(int key) {
int idx = getHash(key);
while (m[idx] != null) {
if (m[idx].key == key) {
return m[idx].value;
}
++idx;
idx %= capacity;
}
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 idx = getHash(key);
while (m[idx] != null) {
if (m[idx].key == key) {
m[idx] = new Node(-1, -1);
--size;
return;
}
++idx;
idx %= capacity;
}
}
}