用数组存储就是将数映射到对值取模的数组上,将这个值定为质数能减少冲突。
哈希——拉链法:
#include<iostream>
#include<cstring>
using namespace std;
const int N=100003;
int e[N],ne[N],h[N],idx;
void insert(int x) {
int t=(x%N+N)%N;
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,m;
cin>>n;
char op[2];
memset(h,-1,sizeof h);
for(int i=1; i<=n; i++) {
cin>>op>>m;
if(op[0]=='I') {
insert(m);
} else if(op[0]=='Q') {
if(find(m)) {
cout<<"Yes"<<endl;
} else {
cout<<"No"<<endl;
}
}
}
return 0;
}
利用单链表存储,当遇到冲突就在同一个数组以指针相连形成拉链;
哈希——开放寻址法:
#include<iostream>
#include<cstring>
using namespace std;
const int N=200003,null=0x3f3f3f3f;
int h[N];
int find(int x){
int t=(x%N+N)%N;
while(h[t]!=null&&h[t]!=x){
t++;
if(h[t]==x){
t=0;
}
}
return t;
}
int main(){
int n,m;
cin>>n;
char op[2];
memset(h,null,sizeof h);
for(int i=1;i<=n;i++){
cin>>op>>m;
if(op[0]=='I'){
int k=find(m);
h[k]=m;
}else if(op[0]=='Q'){
int k=find(m);
if(h[k]==m){
cout<<"Yes"<<endl;
}else {
cout<<"No"<<endl;
}
}
}
return 0;
}
其中最重要的是find函数,当所找的数组已经有人时,将往后找,直到找到空余的位置,输出k,将数值存入h [ k ];如果超出N,就将 t 回到 0 再找;
定义空余位置的数定为0x3f3f3f3f,比1e9大;
find函数输出的值在插入中为空的数组的位置,在寻找中为存储这个数的位置;