import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Set<String> set = new HashSet<>();
int n = Integer.parseInt(br.readLine());
String[] arr1 = br.readLine().split(" ");
for(String s : arr1) set.add(s);
int m = Integer.parseInt(br.readLine());
String[] arr2 = br.readLine().split(" ");
for(String s : arr2){
if(set.contains(s)) System.out.println(1);
else System.out.println("0");
}
br.close();
}
}
이진 탐색을 이용한 풀이 (Arrays.sort() 때문인지 시간 초과가 났다.)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
int M = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) {
boolean found = false;
int target = Integer.parseInt(st.nextToken());
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int midIndex = (start + end) / 2;
int midValue = arr[midIndex];
if (midValue > target)
end = midIndex;
else if (midValue < target)
start = midIndex + 1;
else {
found = true;
break;
}
}
if (found) System.out.println(1);
else System.out.println(0);
}
}
}
'Coding Test > 백준' 카테고리의 다른 글
[백준/자바] 10828 - 스택 (0) | 2023.05.11 |
---|---|
[백준/자바] 2751 - 수 정렬하기 2 (0) | 2023.05.09 |
[백준/자바] 10988 - 팰린드롬인지 확인하기 (0) | 2023.05.08 |
[백준/자바] 5622 - 다이얼 (0) | 2023.05.08 |
[백준/자바] 2908 - 상수 (0) | 2023.05.08 |