数据结构实验之查找七:线性之哈希表

本文通过解决SDUT题目实例,介绍了哈希表结合线性探测法的应用技巧,并对比了因数组大小配置不当导致的错误答案与正确答案代码,强调了合理设置哈希表容量的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Think:
1知识点:哈希表+线性探测法
2反思:哈希表+线性探测法,数组要开大一点?

SDUT题目链接

以下为Wrong Answer代码——数组开小了?

#include <bits/stdc++.h>

using namespace std;

int main(){
    int hash[1004], pos[1004];
    int n, p, i, k, kk, tp;
    while(scanf("%d %d", &n, &p) != EOF){
        tp = 0;
        memset(hash, -1, sizeof(hash));
        for(i = 0; i < n; i++){
            scanf("%d", &k);
            kk = k % p;
            if(hash[kk] == -1){
                hash[kk] = k;
            }
            else {
                int add = 0;
                int t = kk;
                while(hash[t] != -1){
                    t = (kk + add) % p;
                    if(hash[t] == k){
                        break;
                    }
                    add++;
                }
                hash[t] = k;
                kk = t;
            }
            pos[tp++] = kk;
        }
        for(i = 0; i < n; i++)
            printf("%d%c", pos[i], i == n-1? '\n': ' ');
    }
    return 0;
}


/***************************************************
User name: 
Result: Wrong Answer
Take time: 0ms
Take Memory: 224KB
Submit time: 2017-07-14 21:35:33
****************************************************/

以下为Accepted代码

#include <bits/stdc++.h>

using namespace std;

int main(){
    int hash[1104], pos[1104];
    int n, p, i, k, kk, tp;
    while(scanf("%d %d", &n, &p) != EOF){
        tp = 0;
        memset(hash, -1, sizeof(hash));
        for(i = 0; i < n; i++){
            scanf("%d", &k);
            kk = k % p;
            if(hash[kk] == -1){
                hash[kk] = k;
            }
            else {
                int add = 0;
                int t = kk;
                while(hash[t] != -1){
                    t = (kk + add) % p;
                    if(hash[t] == k){
                        break;
                    }
                    add++;
                }
                hash[t] = k;
                kk = t;
            }
            pos[tp++] = kk;
        }
        for(i = 0; i < n; i++)
            printf("%d%c", pos[i], i == n-1? '\n': ' ');
    }
    return 0;
}

/***************************************************
User name: 
Result: Accepted
Take time: 0ms
Take Memory: 228KB
Submit time: 2017-07-14 22:02:25
****************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值