两种哈希的理解

 用数组存储就是将数映射到对值取模的数组上,将这个值定为质数能减少冲突。

哈希——拉链法:

#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大; 

0x3f 和 memset

find函数输出的值在插入中为空的数组的位置,在寻找中为存储这个数的位置;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值