哈希表(模拟散列表)

什么是哈希表?

来吧!一文彻底搞定哈希表!_庆哥Java的CSDN技术博客-CSDN博客

题目:

哈希表(模拟散列表)_第1张图片

代码:

拉链法:

#include 
#include 

using namespace std;

const int N = 100003;  //减少冲突:数组长度一般取离2的整数幂较远的质数

int h[N], e[N], ne[N], idx;  //h[]是开的一个槽,e[]是链表当前的数值,ne[]是链表中的下一个位置,idx表示当前用到的位置

//插入
void insert(int x)
{
    int k = (x % N + N) % N;   //哈希函数将x映射到0~10e5之间,+N后再%N使结果k变成正数
    e[idx] = x;
    ne[idx] = h[k];
    h[k] = idx ++ ;
}

//查询
bool find(int x)
{
    int k = (x % N + N) % N;
    for (int i = h[k]; i != -1; i = ne[i])  //空指针的下标为-1
        if (e[i] == x)
            return true;

    return false;
}

int main()
{
    int n;
    cin>>n;

    memset(h, -1, sizeof h);  //清空槽 空指针一般用 -1 来表示

    while (n -- )
    {
        char op[2];
        int x;
        scanf("%s%d", op, &x);  //scanf读入一个字符串,会自动把空格,回车,制表符忽略掉

        if (*op == 'I') insert(x);
        else
        {
            if (find(x)) puts("Yes");
            else puts("No");
        }
    }

    return 0;
}

 开放寻址法:

#include 
#include 
using namespace std;
const int N = 200003;  //减少冲突:数组范围开到题目要求的2~3倍,并且是大于20000的最小质数
const int null = 0x3f3f3f3f;   //标志:说明该位置为空,该数不在x的范围内
int h[N];

//如果x在哈希表中的位置存在,返回x的位置;如果x在哈希表中的位置不存在,返回它应该存储的位置
int find(int x)
{
    int t = (x % N + N) % N;
    while (h[t] != null && h[t] != x)   
    {
        t ++ ;
        if (t == N) t = 0;
    }
    return t;
}

int main()
{
    memset(h, 0x3f, sizeof h);

    int n;
    scanf("%d", &n);

    while (n -- )
    {
        char op[2];
        int x;
        scanf("%s%d", op, &x);
        if (*op == 'I') h[find(x)] = x;
        else
        {
            if (h[find(x)] == null) puts("No");
            else puts("Yes");
        }
    }

    return 0;
}

 

你可能感兴趣的:(数据结构,散列表,数据结构,算法,c++)