acwing自我学习笔记-模拟散列表 840

这篇博客介绍了两种哈希表的实现方法:拉链法和开放寻址法。通过C++代码展示了如何在哈希表中插入元素并查找元素。拉链法利用数组代替结构体构建链表,而开放寻址法通过探测序列解决冲突。这两个方法在处理数据存储和查找效率上有不同的优缺点。
摘要由CSDN通过智能技术生成

//拉链法

#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5 + 3;

int h[N],e[N], ne[N], idx;//拉链法,用数组方式代替struct结构方式构造链表,ne[]指向下个结点的位置

void Insert(int x)
{
    int t = (x % N+N)%N;//hash值
    e[idx] = x;
    ne[idx] = h[t];
    h[t]=idx++;
}

bool Find(int x)
{
    int t = (x % N + N) % N;
  
    for (int i = h[t]; i != -1; i = ne[i])
    {
        if (e[i] == x)
        {
            return true;
        }
    }
    return false;
}

int main()
{
    int n;
    cin >> n;
    string op;
    int x;
    memset(h, -1, sizeof(h));
    while(n--)
    {
        cin >> op>>x;
        if ("I" == op)
        {
            Insert(x);
        }
        else
        {
            if (Find(x))
            {
                cout << "Yes" << endl;
            }
            else
            {
                cout << "No" << endl;
            }
        }
    }
    return 0;
}

//开放定址法

#include <iostream>
#include <cstring>
using namespace std;
const int N =2e5+3,null= 0x3f3f3f3f;

int h[N];//开放寻址法,数组开操作的2~3倍避免冲突
bool Find(int x);

void Insert(int x)
{
    int t = (x % N + N) % N;//hash值
    if(!Find(x))//没有重复出现
    {
        while(h[t] != 0x3f3f3f3f && h[t]!=x && t<=N)
        {
            t++;
        }
        h[t] = x;//插入x
    }
}

bool Find(int x)
{
    int t = (x % N + N) % N;
    while (h[t] != 0x3f3f3f3f && h[t] != x && t <= N)
    {
        t++;
    }
    if (h[t] == 0x3f3f3f3f)
    {
        return false;
    }
    return true;
}

int main()
{
    int n;
    cin >> n;
    string op;
    int x;
    memset(h, 0x3f, sizeof(h));
    while (n--)
    {
        cin >> op >> x;
        if ("I" == op)
        {
            Insert(x);
        }
        else
        {
            if (Find(x))
            {
                cout << "Yes" << endl;
            }
            else
            {
                cout << "No" << endl;
            }
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值