当前位置:网站首页>补坑 模拟散列表
补坑 模拟散列表
2022-08-08 05:42:00 【一条小小yu】
题目:

map也能做,主要学一下hash表的实现方式,之前3、4月份的时候疯狂补坑备考,但是选择了洛谷和b站,现在看来还是acwing比较好,因为有视频。
拉链法代码
拉链法就是1-N,然后每个i一个链表,感觉挺好理解,上代码。
#include <cstring>
#include <iostream>
using namespace std;
const int N = 1e5 + 3; // 取大于1e5的第一个质数,取质数冲突的概率最小 可以百度
//* 开一个槽 h
int h[N], e[N], ne[N], idx; //邻接表
void insert(int x) {
// c++中如果是负数 那他取模也是负的 所以 加N 再 %N 就一定是一个正数
int k = (x % N + N) % N;
e[idx] = x;
ne[idx] = h[k];
h[k] = idx++;
}
bool find(int x) {
//用上面同样的 Hash函数 讲x映射到 从 0-1e5 之间的数
int k = (x % N + N) % N;
for (int i = h[k]; i != -1; i = ne[i]) {
if (e[i] == x) {
return true;
}
}
return false;
}
int n;
int main() {
cin >> n;
memset(h, -1, sizeof h); //将槽先清空 空指针一般用 -1 来表示
while (n--) {
string op;
int x;
cin >> op >> x;
if (op == "I") {
insert(x);
} else {
if (find(x)) {
puts("Yes");
} else {
puts("No");
}
}
}
return 0;
}
开放寻址法:
#include <cstring>
#include <iostream>
using namespace std;
//开放寻址法一般开 数据范围的 2~3倍, 这样大概率就没有冲突了
const int N = 2e5 + 3; //大于数据范围的第一个质数
const int null = 0x3f3f3f3f; //规定空指针为 null 0x3f3f3f3f
int h[N];
int find(int x) {
int t = (x % N + N) % N;
while (h[t] != null && h[t] != x) {
t++;
if (t == N) {
t = 0;
}
}
return t; //如果这个位置是空的, 则返回的是他应该存储的位置
}
int n;
int main() {
cin >> n;
memset(h, 0x3f, sizeof h); //规定空指针为 0x3f3f3f3f
while (n--) {
string op;
int x;
cin >> op >> x;
if (op == "I") {
h[find(x)] = x;
} else {
if (h[find(x)] == null) {
puts("No");
} else {
puts("Yes");
}
}
}
return 0;
}
边栏推荐
- 神经网络参数量和计算量,神经网络是参数模型吗
- Session 和 Cookie 使用
- Typescript namespace
- 分布式事务 :可靠消息最终一致性方案
- sqlmap+dnslog注入复现
- 【图像处理】matlab基础图像处理 | 图像载入、图像添加噪声、图像滤波、图像卷积
- 0 dictionary tree/string medium LeetCode676. Implement a magic dictionary
- Redis In Action —— Advanced —— 数据主从同步原理 —— 全量同步 与 增量同步 工作流程及原理 —— 以及如何利用 docker 容器技术快速模拟单机 Redis 集群
- [Redis] Redis Learning - Transaction
- Day8:面试必考编程题(细心OJ)
猜你喜欢

文件操作 - IO

【着色器实现Tricolor三原色型变效果_Shader效果第十八篇】

卷积神经网络 图像识别,卷积神经网络 图像处理

数据库分库分表,何时分?怎样分?

Matlab simulation of photovoltaic mppt maximum power control based on disturbance observation method

Style of DataGrid in wpf

14. Unity2D horizontal version particle system special effects: blood particles + high landing particles + object pool to manage all particles

Redis设置开机自启动

Checkerboard Coloring Problem

Day8:面试必考编程题(细心OJ)
随机推荐
卷积神经网络的基本操作,卷积神经网络卷积计算
LVS:NAT模式详解
云计算和云服务,云计算
分布式事务 :可靠消息最终一致性方案
Typescript 命名空间
Hard Disk Basics
[Untitled] I haven't thought of a name yet
Servlet---ServletConfig类使用介绍
Web attack log analysis: a guide for beginners
棋盘染色问题
让你的应用完美适配平板
76. The minimum cover substring
Typescript namespace
Mail online cobalstrike fishing
Web 攻击的日志分析:初学者指南
IP核之RAM实验
字符串题目解析
28.异常检测
Web Application Vulnerability Assessment with Zap and W3af
Preprocessing Notes