1.hash表
拉链法
import java.io.*;
public class Main{
static int N = 100010;
static int[] h = new int[N];
static int[] e = new int[N];
static int[] ne = new int[N];
static int idx;
static void insert(int x){
int k = (x%N+N)%N;
e[idx] = x;
ne[idx] = h[k];
h[k] = idx++;
}
static boolean 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;
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(br.readLine());
for(int i=0;i<N;i++){
h[i]=-1;
}
while(n-->0){
String[] s = br.readLine().split(" ");
int x = Integer.valueOf(s[1]);
if(s[0].equals("I")){
insert(x);
}else{
if(find(x)) System.out.println("Yes");
else System.out.println("No");
}
}
}
}
开放寻址法
import java.io.*;
public class Main{
static int N = 100003;
static int[] h = new int[N];
static int bound = (int)(1e9+1);
static int find(int x){
int k = (x%N+N)%N;
while(h[k]!=bound && h[k]!=x){
k++;
}
return k;
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(br.readLine());
for(int i=0;i<N;i++){
h[i]=bound;
}
while(n-->0){
String[] s = br.readLine().split(" ");
int x = Integer.valueOf(s[1]);
if(s[0].equals("I")){
h[find(x)]=x;
}else{
if(h[find(x)]!=bound) System.out.println("Yes");
else System.out.println("No");
}
}
}
}
字符串hash
import java.io.*;
public class Main{
static int N = 100010;
static int P = 131;
static char[] c = new char[N];
static long[] p = new long[N];
static long[] h = new long[N];
static long get(int l,int r){
return h[r]-h[l-1]*p[r-l+1];
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
int n = Integer.valueOf(s[0]);
int m = Integer.valueOf(s[1]);
String str = br.readLine();
p[0] = 1;
for(int i=1;i<=n;i++){
c[i] = str.charAt(i-1);
p[i] = p[i-1]*P;
h[i] = h[i-1]*P + c[i];
}
while(m-->0){
String[] strs = br.readLine().split(" ");
int l1 = Integer.valueOf(strs[0]);int r1 = Integer.valueOf(strs[1]);
int l2 = Integer.valueOf(strs[2]);int r2 = Integer.valueOf(strs[3]);
if(get(l1,r1)==get(l2,r2)) System.out.println("Yes");
else System.out.println("No");
}
}
}