哈希表-开放寻址法-拉链法

开放寻址法和拉链法十分类似,只是处理冲突的方式不一样。拉链法通过在冲突位置开链表解决,开放寻址法通过往后顺次找空位置解决。

拉链法:
在这里插入图片描述

#include<iostream>
#include<cstdio>
#include<vector>

using namespace std;

const int N = 1e5+3;

vector<int > h[N];

int _hash(int x){
    return (x%N+N)%N;
}

void insert(int x){
    int p = _hash(x);
    h[p].push_back(x);
}

bool find(int x){
    int p=_hash(x);
    for(int k:h[p]){
        if(k==x)
            return true;
    }
    return false;
}

int main(){
    int t;
    cin>>t;
    while(t--){
        char d[2];
        int x;
        scanf("%s%d",d,&x);
        if(d[0]=='I') insert(x);
        else{
            if(find(x))
                puts("Yes");
            else
                puts("No");
        }
    }
    return 0;
}

开放寻址法:
在这里插入图片描述

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

const int N = 1e5+3<<2, null = 0x3f3f3f3f;

int h[N];

int _hash(int x){
    return (x%N+N)%N;
}

int find(int x){
    int p=_hash(x);
    while(h[p]!=null&&h[p]!=x){
        p++;
        if(p==N){
            p=0;
        }
    }
    return p;
}

int main(){
    int t;
    cin>>t;
    memset(h,null,sizeof h);
    while(t--){
        char d[2];
        int x;
        scanf("%s%d",d,&x);
        if(d[0]=='I') h[find(x)] = x;
        else{
            if(h[find(x)]!=null)
                puts("Yes");
            else
                puts("No");
        }
    }
    return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值