hash表的模版

//拉链法hash
#include<cstring>
#include<iostream>
using namespace std;

const int N = 100005;
int h[N],e[N],ne[N],idx = 0;//h[N]是hash表,e[N]、ne[ne]、idx分别为链表值、下一个结点、当前结点

void insert(int x)
{
    int k = (x % N + N) % N;//取模映射,+N是为了将负数变成正数
    e[idx] = x;
    ne[idx] = h[k];
    h[k] = idx++;//在k位置插入当前数
}

bool find(int x)
{
    int k = (x % N + N)%N;
    for(int i = h[k];i != -1;i = ne[i])
    {
        if(e[i] == x)return true;//链表遍历,找到是否有x
    }
    return false;
}

int main()
{
    int n;
    cin>>n;
    
    memset(h,-1,sizeof(h));//将h初始化为-1
    
    while(n--)
    {
        char op;
        int x;
        cin>>op;
        cin>>x;
        if(op == '1')insert(x);
        else
        {
            if(find(x))cout<<"yes"<<endl;
            else cout<<"No"<<endl;
        }
    }
    
    return 0;
}

//开放寻址法
#include<iostream>
using namespace std;
const int N = 200003,null = 0x3f3f3f3f;//null是10^9
int h[N];

int find(int x)
{
    int k = (x % N + N)%N;//取模映射,+N是为了将负数变成正数
    while(h[k] != null&&h[k] != x)
    {
        k++;
        if(k == N)k = 0;
    }//如果当前位置被占,找到下一个位置
    return k;
}
int main()
{
    int n;
    cin>>n;
    memset(h,0x3f,sizeof(h));
    while(n--)
    {
        char op;
        int x;
        cin>>op>>x;
        int k = find(x);
        if(op == '1')h[k] = x;
        else
        {
            if(h[k] != null)cout<<"Yes"<<endl;
            else cout<<"No"<<endl;
        }
    }
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七七七_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值