Keep going
백준 1920번 : 수찾기 본문
1920번: 수 찾기
첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들
www.acmicpc.net

일반적인 탐색 알고리즘 문제다.
배열에 찾는 값이 있으면 1을 출력하고 없으면 0을 반환하는 이진 탐색하는 메소드를 만들었다.
import java.util.*;
public class SearchNumber {
static int binarySearch(int[] a, int key) {
int cl = 0;
int cr = a.length - 1;
while (cl <= cr) {
int cs = (cl + cr) / 2;
if (key == a[cs])
return 1;
else if (key > a[cs]) {
cl = cs + 1;
} else
cr = cs - 1;
}
return 0;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] ar = new int[n];
for (int i = 0; i < ar.length; i++) {
ar[i] = input.nextInt();
}
Arrays.sort(ar);
int r = input.nextInt();
for (int i = 0; i < r; i++) {
System.out.println(binarySearch(ar, input.nextInt()));
}
}
}
|
cs |
실행 결과
