ALGORITHM
백준 1920 수 찾기 (Java)
공부하는_다온
2023. 3. 29. 22:57
1. 문제 링크
1920번: 수 찾기
첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들
www.acmicpc.net
2. 문제 및 입출력예제
3. 문제 풀이
그냥 모든 수를 입력받고 찾는다면 시간 초과가 난다.
이진 탐색을 해야 하는데 정렬 후 jdk 메서드 중 하나인 이분 탐색을 이용했다.
값이 음수가 나올 경우에는 목록에 값이 없는 것이고, 양수면 존재하는 것이다.
4. 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
static StringBuilder sb;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
int[] A = new int[N];
String[] split = br.readLine().split(" ");
for(int i=0;i<N;i++) {
A[i] = Integer.parseInt(split[i]);
}
Arrays.sort(A);
int M = Integer.parseInt(br.readLine());
split = br.readLine().split(" ");
for(int i=0;i<M;i++) {
if(Arrays.binarySearch(A, Integer.parseInt(split[i])) < 0){
sb.append(0).append("\n");
}
else {
sb.append(1).append("\n");
}
}
System.out.println(sb);
}
}