哈希表

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
复制代码

 <2> 开放寻址法

复制代码
 1 /*
 2  * Project: 11_哈希表
 3  * File Created:Sunday, January 17th 2021, 4:39:01 pm
 4  * Author: Bug-Free
 5  * Problem:AcWing 840. 模拟散列表  开放寻址法
 6  */
 7 #include <cstring>
 8 #include <iostream>
 9 
10 using namespace std;
11 
12 //开放寻址法一般开 数据范围的 2~3倍, 这样大概率就没有冲突了
13 const int N = 2e5 + 3;        //大于数据范围的第一个质数
14 const int null = 0x3f3f3f3f;  //规定空指针为 null 0x3f3f3f3f
15 
16 int h[N];
17 
18 int find(int x) {
19     int t = (x % N + N) % N;
20     while (h[t] != null && h[t] != x) {
21         t++;
22         if (t == N) {
23             t = 0;
24         }
25     }
26     return t;  //如果这个位置是空的, 则返回的是他应该存储的位置
27 }
28 
29 int n;
30 
31 int main() {
32     cin >> n;
33 
34     memset(h, 0x3f, sizeof h);  //规定空指针为 0x3f3f3f3f
35 
36     while (n--) {
37         string op;
38         int x;
39         cin >> op >> x;
40         if (op == "I") {
41             h[find(x)] = x;
42         } else {
43             if (h[find(x)] == null) {
44                 puts("No");
45             } else {
46                 puts("Yes");
47             }
48         }
49     }
50     return 0;
51 }
View Code
复制代码

 

posted @   rw156  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示