이분 탐색
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class baekjoon2776 {
public static int binarySearch(int[] arr,int start, int end, int target){
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] < target) {
start = mid + 1;
} else if (arr[mid] > target) {
end = mid - 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int T = Integer.parseInt(br.readLine());
while(T-- > 0){
StringBuffer sb = new StringBuffer();
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
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++){
if(binarySearch(arr,0,N-1,Integer.parseInt(st.nextToken())) == -1){
if (i != M - 1) {
sb.append(0).append("\n");
} else {
sb.append(0);
}
}else {
if (i != M - 1) {
sb.append(1).append("\n");
} else {
sb.append(1);
}
}
}
System.out.println(sb);
}
}
}
집합 자료구조 활용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class baekjoon2776 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static StringBuilder sb;
public static void main(String args[])throws IOException{
int T = Integer.parseInt(br.readLine());
while(T!=0){
sb = new StringBuilder();
Set<Integer> set = new HashSet<>();
int N = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
for(int i=0;i<N;i++){
set.add(Integer.parseInt(st.nextToken()));
}
int M = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
for(int i=0;i<M;i++){
sb.append(set.contains(Integer.parseInt(st.nextToken()))? 1: 0).append("\n");
}
System.out.print(sb);
T--;
}
}
}
List로도 풀고 다해봤는데, 어떻게 푸는지는 알겠는데, 백준 제출할때 계속 시간초과가 나서 다른 방법으로 풀었다.
시간제한만 안걸리면 괜찮은 문제같은데 시간제한도 턱걸이로 통과하니까 더어렵게 느껴지는것 같다.