拉链法
其实就是在h[x]处边上引出一条串上面挂着对应的数(链表
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e5+3;
int h[N], e[N], ne[N], idx;
void insert(int x) {
int k = (x % N + N) % N;
//防止出现负数 以及N尽量取离2的整次幂远的质数 这样冲突的概率最小
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]) {
if (e[i] == x)return true;
}
return false;
}
int main() {
memset(h, -1, sizeof h);
int n;
cin >> n;
while (n--) {
string s;
int x;
cin >> s >> x;
if (s == "I") {
insert(x);
}
else {
if (find(x)) {
printf("Yes\n");
}
else printf("No\n");
}
}
}
开放寻址法
我愿称之为找蹲坑法(
#include<iostream>
#include<cstring>
using namespace std;
const int N = 2e5+3;//开放寻址法一般会把数组开到大约2~3倍减少冲突
int h[N],null=0x3f3f3f3f;
int find(int x) {//用于返回x应该插入的位置
int t = (x % N + N) % N;
while (h[t] != null && h[t] != x) {//当这个位置已经被占了并且这个位置不是x的时候
//如果没有被占说明不存在这个数那就放到这个位置
//如果是x那这个位置就应该是
//不考虑冲突?
t++;
if (t == N)t = 0;//如果一圈下来没找到那就从头开始
}
return t;
}
int main() {
int n;
memset(h, 0x3f, sizeof h);//使h都指向空
cin >> n;
while (n--) {
string s;
int x;
cin >> s >> x;
if (s == "I") {
h[find(x)] = x;
}
else {
if (h[find(x)] == null)puts("No");//如果找到的坑位没有被赋值
else puts("Yes");
}
}
}