博客
关于我
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/

    你可能感兴趣的文章
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>