博客
关于我
7-7 整型关键字的散列映射 (25分)
阅读量:357 次
发布时间:2019-03-04

本文共 1433 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要使用哈希表来存储一系列整型关键字,并用线性探测法解决哈希冲突。以下是详细的解决方案:

方法思路

  • 哈希函数:使用除留余数法将关键字映射到哈希表中的位置。具体来说,哈希函数 h = k % P 将关键字 k 映射到位置 h
  • 线性探测法:解决哈希冲突。当一个位置被占据时,线性探测法会沿着散列表线性递增的位置寻找下一个空位。
  • 初始化:创建两个数组 flagindex,分别用于记录每个位置是否被占用以及每个关键字的位置。
  • 处理输入:读取输入数据,包含关键字数量 N 和哈希表的长度 P,以及 N 个关键字。
  • 存储关键字:逐个处理每个关键字,计算其哈希值并记录到哈希表中,使用线性探测法解决冲突。
  • 解决代码

    #include 
    #include
    int main() { int n, p; scanf("%d %d", &n, &p); int keys[n]; for (int i = 0; i < n; ++i) { keys[i] = 0; scanf("%d", keys + i); } int flag[p] = {0}; int index[n] = {0}; for (int i = 0; i < n; ++i) { int k = keys[i]; int h = k % p; if (flag[h] == 0) { index[i] = h; flag[h] = 1; } else { int j = h + 1; while (true) { if (j >= p) { j = 0; } if (flag[j] == 0) { index[i] = j; flag[j] = 1; break; } j++; } } } for (int i = 0; i < n; ++i) { if (i != 0) { printf(" "); } printf("%d", index[i]); } printf("\n"); return 0;}

    代码解释

  • 读取输入:首先读取 NP,然后读取 N 个关键字。
  • 初始化数组flag 数组用于记录每个位置是否被占用,index 数组记录每个关键字的位置。
  • 处理每个关键字:计算每个关键字的哈希值,并检查该位置是否可用。如果可用,记录该位置并标记;如果不可用,使用线性探测法找到下一个空位。
  • 输出结果:按顺序输出每个关键字的位置。
  • 这种方法确保了每个关键字都能正确地存储到哈希表中,并且在发生冲突时能够高效地找到下一个空位。

    转载地址:http://floe.baihongyu.com/

    你可能感兴趣的文章
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>
    npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
    查看>>
    npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
    查看>>