BOJ #1920
https://www.acmicpc.net/problem/1920
N개의 정수 A[1], A[2], …, A[N]이 주어져 있을 때, 이 안에 X라는 정수가 존재하는지 알아내는 프로그램을 작성하시오.
첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들이 A안에 존재하는지 알아내면 된다. 모든 정수의 범위는 -231 보다 크거나 같고 231보다 작다.
M개의 줄에 답을 출력한다. 존재하면 1을, 존재하지 않으면 0을 출력한다.
import java.util.Scanner;
import java.util.Arrays;
class Main {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int i = 0; i<n; i++ ) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
int m = sc.nextInt();
int b[] = new int[m];
for (int i = 0; i<m; i++) {
b[i] = sc.nextInt();
System.out.println(binarySearch(a, b[i]));
}
sc.close();
}
private static int binarySearch(int[] a, int n) {
int first = 0;
int last = a.length -1;
int mid = 0;
while (first <= last) {
mid = (first + last) /2;
if (n == a[mid]) return 1;
else {
if (n < a[mid]) last = mid -1;
else first = mid + 1;
}
}
return 0;
}
}
어렵지 않게 풀었다 룰루~!