输入有多组数据。 每组输入n,然后输入n个整数,再输入m,然后再输入m个整数(1<=m,n<=100)。
如果在n个数组中输出YES否则输出NO。
5 1 5 2 4 3 3 2 5 6
YES YES NO
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
/**
* 二分排序的关键就是要先排序;
* */
public static boolean binSearch(int[] nums, int number) {
int left = 0;
int right = nums.length - 1;
boolean judge = false;
while (left <= right) {
int middle = (left + right) / 2;
if (nums[middle] < number) {
left = middle + 1;
} else if (nums[middle] > number) {
right = middle - 1;
} else {
return true;
}
}
return false;
}
public static void main(String[] args) {
int number;
int Max=100;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
number = scanner.nextInt();
int[] nums = new int[number];
for (int i = 0; i < number; i++) {
nums[i] = scanner.nextInt();
}
Arrays.sort(nums);
int m = scanner.nextInt();
for (int i = 0; i < m; i++) {
int target;
target = scanner.nextInt();
if (binSearch(nums, target)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
}
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int na = Integer.parseInt(br.readLine()); String[] a = br.readLine().split(" "); int[] aa = new int[na]; for (int i = 0; i < na; i++) { aa[i] = Integer.parseInt(a[i]); } Arrays.sort(aa); int nb = Integer.parseInt(br.readLine()); String[] b = br.readLine().split(" "); int[] bb = new int[nb]; for (int i = 0; i < nb; i++) { bb[i] = Integer.parseInt(b[i]); } for (int i = 0; i < nb; i++) { if (Arrays.binarySearch(aa, bb[i]) >=0) { System.out.println("YES"); } else System.out.println("NO"); } } }
import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) set.add(scanner.nextInt()); int m = scanner.nextInt(); for (int i = 0; i < m; i++) System.out.println(set.contains(scanner.nextInt())?"YES":"NO"); } }
运行时间:49ms
占用内存:10964k
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int n = scan.nextInt();
int[] arr1 = new int[n];
for (int i = 0; i < n; i++) {
arr1[i] = scan.nextInt();
}
int m = scan.nextInt();
int[] arr2 = new int[m];
for (int i = 0; i < m; i++) {
arr2[i] = scan.nextInt();
}
int count = 0;
for (int i = 0; i < arr2.length; i++) {
int temp = arr2[i];
for (int j = 0; j < arr1.length; j++) {
if (temp == arr1[j]) {
System.out.println("YES");
break;
} else {
count++;
}
if (count == n) {
System.out.println("NO");
}
}
count = 0;
}
}
}
}