forked from seanprashad/leetcode-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path706_Design_HashMap.java
96 lines (76 loc) · 1.89 KB
/
706_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
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
classMyHashMap {
privateclassNode {
privateintkey, value;
publicNode(intk, intv) {
key = k;
value = v;
}
}
privateNode[] m;
privateintsize, capacity;
privatestaticfinaldoubleLOAD_CAPACITY = 0.66;
publicMyHashMap() {
size = 0;
capacity = 5000;
m = newNode[capacity];
}
privateintgetHash(intkey) {
returnkey % capacity;
}
privatevoidresize() {
if (size <= LOAD_CAPACITY * capacity) {
return;
}
size = 0;
capacity *= 2;
Node[] temp = m;
m = newNode[capacity];
for (inti = 0; i < temp.length; i++) {
if (temp[i] == null || temp[i].key == -1) {
continue;
}
put(temp[i].key, temp[i].value);
}
}
publicvoidput(intkey, intvalue) {
intidx = getHash(key);
while (m[idx] != null) {
if (m[idx].key == key) {
m[idx].value = value;
return;
}
++idx;
idx %= capacity;
}
m[idx] = newNode(key, value);
++size;
resize();
}
publicintget(intkey) {
intidx = getHash(key);
while (m[idx] != null) {
if (m[idx].key == key) {
returnm[idx].value;
}
++idx;
idx %= capacity;
}
return -1;
}
/**
* Removes the mapping of the specified value key if this map contains a mapping
* for the key
*/
publicvoidremove(intkey) {
intidx = getHash(key);
while (m[idx] != null) {
if (m[idx].key == key) {
m[idx] = newNode(-1, -1);
--size;
return;
}
++idx;
idx %= capacity;
}
}
}