AcWing 840. 模拟散列表 -- java 语言
原题链接
简单
作者:
dotasf
,
2025-02-07 11:24:05
,
所有人可见
,
阅读 1
package com.icewei.alg.leetcode.acwing.chapter1.basicalgo2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class Hash {
private static int N = 100010;
private static int idx = 0;
private static int[] h = new int[N];
private static int[] e = new int[N];
private static int[] ne = new int[N];
private static void insert(int x) {
int k = (x % N + N) % N;
e[idx] = x; ne[idx] = h[k];
h[k] = idx++;
}
private 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;
}
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StreamTokenizer st = new StreamTokenizer(br);
public static void main(String[] args) throws IOException {
st.nextToken(); int n = (int)st.nval;
Arrays.fill(h, -1);
while (n-- > 0) {
st.nextToken(); String op = st.sval;
st.nextToken(); int x = (int)st.nval;
if ("I".equals(op)) {
insert(x);
} else {
System.out.println(find(x) ? "Yes":"No");
}
}
}
static class Kaifangxunzhifa {
private static int N = 100010;
private static int NULL_POSITION = 0x3f3f3f3f;
private static int[] h = new int[2*N];
private static int find(int x) {
int k = (x % N + N) % N;
while (h[k] != NULL_POSITION && h[k] != x) {
k++;
if (k == N) k = 0;
}
return k;
}
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StreamTokenizer st = new StreamTokenizer(br);
public static void main(String[] args) throws IOException {
st.nextToken(); int n = (int)st.nval;
Arrays.fill(h, NULL_POSITION);
while (n-- > 0) {
st.nextToken(); String op = st.sval;
st.nextToken(); int x = (int)st.nval;
int k = find(x);
if ("I".equals(op)) {
h[k] = x;
} else {
System.out.println(h[k] != NULL_POSITION ? "Yes":"No");
}
}
}
}
}