lurenaa的博客

😂代码实现

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
class MyHashMap {
public:
/** Initialize your data structure here. */
MyHashMap() :
N(0), M(10000)
{
keys = new int [10000]();
vals = new int [10000]();
for(int i = 0; i < 10000; ++i) {
keys[i] = -1;
vals[i] = -1;
}
}

/** value will always be non-negative. */
void put(int key, int value) {
int i = (key & 0x7fffffff) % M;
for( ; keys[i] != -1; i = (i + 1) % M) {
if(keys[i] == key) {
vals[i] = value;
return ;
}
}
vals[i] = value;
keys[i] = key;
N++;
}

/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int get(int key) {
int i = (key & 0x7fffffff) % M;
for( ; keys[i] != -1; i = (i + 1) % M) {
if(keys[i] == key)
return vals[i];
}
return -1;
}

/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
int i = (key & 0x7fffffff) % M;
for( ; keys[i] != -1; i = (i + 1) % M) {
if(keys[i] == key)
break;
}
if(keys[i] == -1)
return ;
int k2, v2;
keys[i] = -1;
vals[i] = -1;
i = (i + 1) % M;
while(keys[i] != -1){
k2 = keys[i];
v2 = vals[i];
keys[i] = -1;
vals[i] = -1;
--N;
put(k2, v2);
i = (i + 1) % M;
}
--N;
}
private:
int *keys;
int *vals;
int N;
int M;
};