拉链法

 1 class MyHashMap 
 2 {
 3 public:
 4     const static int N = 20011;
 5     vector<list<pair<int,int>>> hash;
 6 
 7     MyHashMap() 
 8     {
 9         hash = vector<list<pair<int,int>>>(N);
10     }
11 
12     list<pair<int,int>>::iterator find(int key)
13     {
14         int t = key % N;
15         auto it = hash[t].begin();
16         for (; it != hash[t].end(); it ++ )
17             if (it->first == key)
18                 break;
19         return it;
20     }
21 
22     void put(int key, int value) 
23     {
24         int t = key % N;
25         auto it = find(key);
26         if (it == hash[t].end())
27             hash[t].push_back(make_pair(key, value));
28         else
29             it->second = value;
30     }
31 
32     int get(int key) 
33     {
34         int t = key % N;
35         auto it = find(key);
36         if (it == hash[key % N].end()) return -1;
37         return it->second;
38     }
39 
40     void remove(int key) 
41     {
42         int t = key % N;
43         auto it = find(key);
44         if (it != hash[t].end())
45             hash[t].erase(it);
46     }
47 };

 

posted @ 2020-04-09 17:36  Jinxiaobo0509  阅读(297)  评论(0)    收藏  举报