https://www.acmicpc.net/problem/10815
숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 가지고 있는지 아닌지를 구하는 프로그램을 작성하시오.
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다.
둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다. 두 숫자 카드에 같은 수가 적혀있는 경우는 없다.
셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다.
넷째 줄에는 상근이가 가지고 있는 숫자 카드인지 아닌지를 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다. 이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다
Set 자료구조를 이용해 쉽게 풀 수 있지만, 출제 의도가 이분 탐색인 것 같아서 이분 탐색으로 풀어보았다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
private static final int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}}; //왼위, 위, 오위
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] cards = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < N; i++) {
cards[i] = Integer.parseInt(st.nextToken());
}
int M = Integer.parseInt(br.readLine());
int[] numbers = new int[M];
StringTokenizer st2 = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < M; i++) {
numbers[i] = Integer.parseInt(st2.nextToken());
}
br.close();
solution(cards, numbers);
}
private static void solution(int[] cards, int[] numbers) {
Arrays.sort(cards);
StringBuffer sb = new StringBuffer();
for (int n : numbers) {
int left = 0;
int right = cards.length - 1;
boolean flag = false;
while (left <= right) {
int idx = (left + right) / 2;
if (cards[idx] < n) {
left = idx + 1;
continue;
}
if (cards[idx] > n) {
right = idx - 1;
continue;
}
flag = true;
break;
}
int result = flag ? 1 : 0;
sb.append(result).append(' ');
}
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
}
}