哈希表

发布时间 2023-11-10 00:48:42作者: rw156

1.哈希表的使用

<1> 拉链法

 1 #include <cstring>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 const int N = 1e5 + 3;  // 取大于1e5的第一个质数,取质数冲突的概率最小 可以百度
 7 
 8 //* 开一个槽 h
 9 int h[N], e[N], ne[N], idx;  //邻接表
10 
11 void insert(int x) {
12     // c++中如果是负数 那他取模也是负的 所以 加N 再 %N 就一定是一个正数
13     int k = (x % N + N) % N;
14     e[idx] = x;
15     ne[idx] = h[k];
16     h[k] = idx++;
17 }
18 
19 bool find(int x) {
20     //用上面同样的 Hash函数 讲x映射到 从 0-1e5 之间的数
21     int k = (x % N + N) % N;
22     for (int i = h[k]; i != -1; i = ne[i]) {
23         if (e[i] == x) {
24             return true;
25         }
26     }
27     return false;
28 }
29 
30 int n;
31 
32 int main() {
33     cin >> n;
34 
35     memset(h, -1, sizeof h);  //将槽先清空 空指针一般用 -1 来表示
36 
37     while (n--) {
38         string op;
39         int x;
40         cin >> op >> x;
41         if (op == "I") {
42             insert(x);
43         } else {
44             if (find(x)) {
45                 puts("Yes");
46             } else {
47                 puts("No");
48             }
49         }
50     }
51     return 0;
52 }
View Code