题目
解析
- 哈希表
- 拉链法
- 通过目标数x与一个合适大的质数进行取余运算(注意到负数也要映射到正数中)
- 因为取余后的结果必然会有目标数重复,所以对于取余后的结果数开一个链表,来存放各个数
- 蹲坑法
- 将所有数都依次映射在h[N]一维数组上
- 如果映射结果h[k]上有人,则往后一个空位置上填
- 查找的时候也是同理
代码段
算法一:拉链法
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
const int N=100003;
int h[N],e[N],ne[N],idx;
void add_to_head(int x)
{
int num=abs(x%N);
e[idx]=x;
ne[idx]=h[num];
h[num]=idx++;
}
bool find(int x)
{
int num=abs(x%N);
for(int i=h[num];i!=-1;i=ne[i])
{
if(e[i]==x)return true;
}
return false;
}
int main()
{
int n;cin>>n;
char op;
memset(h,-1,sizeof h);
while(n--)
{
cin>>op;
if(op=='I')
{
int x;cin>>x;
add_to_head(x);
}
else
{
int x;cin>>x;
if(find(x))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
}
}
算法二:蹲坑法
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
const int N=1e5+3,null=0X3f3f3f3f;
int h[N];
int find (int x)
{
int k=abs(x%N);
while(h[k]!=null&&h[k]!=x)
{
k++;
if(k==N)k=0;
}
return k;
}
int main()
{
int n;cin>>n;
memset(h,null,sizeof h);
while(n--)
{
char op;
int x;
cin>>op;
cin>>x;
int k=find(x);
if(op=='I')
h[find(x)]=x;
else
{
if(h[find(x)]==null)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
}
}