|
| 1 | +//BOJ10815 숫자 카드, 실버5 |
| 2 | +//그냥 반복문인 arr.contains(num)를 사용하면 시간초과가 난다. |
| 3 | +//이분 탐색을 사용(재귀로 구현) |
| 4 | +import java.io.*; |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +public class BOJ10815 { |
| 8 | + static int[] arr; |
| 9 | + public static void main(String[] args) throws IOException { |
| 10 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 12 | + StringTokenizer st; |
| 13 | + |
| 14 | + int N = Integer.parseInt(br.readLine()); |
| 15 | + arr = new int[N]; |
| 16 | + |
| 17 | + st = new StringTokenizer(br.readLine()); |
| 18 | + for(int i = 0; i < N; i++) { |
| 19 | + int num = Integer.parseInt(st.nextToken()); |
| 20 | + arr[i] = num; |
| 21 | + } |
| 22 | + |
| 23 | + Arrays.sort(arr); |
| 24 | + |
| 25 | +// for(int cur : arr) { |
| 26 | +// System.out.print(cur + " "); |
| 27 | +// } |
| 28 | +// System.out.println(); |
| 29 | + |
| 30 | + int M = Integer.parseInt(br.readLine()); |
| 31 | + st = new StringTokenizer(br.readLine()); |
| 32 | + for(int i = 0; i < M; i++) { |
| 33 | + int num = Integer.parseInt(st.nextToken()); |
| 34 | + // arr.contains(num)를 사용하면 시간초과가 난다. |
| 35 | + int start = 0; |
| 36 | + int end = arr.length-1; //여기서 -1 안 빼주면 index 에러 발생한다. |
| 37 | + |
| 38 | + int ans = BinarySearch(start, end, num); |
| 39 | + bw.write(ans + " "); |
| 40 | + } |
| 41 | + bw.flush(); |
| 42 | + bw.close(); |
| 43 | + br.close(); |
| 44 | + } |
| 45 | + static int BinarySearch(int start, int end, int num) { |
| 46 | + if(start > end) return 0; |
| 47 | + int mid = (start + end) / 2; |
| 48 | + |
| 49 | + if(arr[mid] == num) { |
| 50 | + return 1; |
| 51 | + }else if(arr[mid] < num) { |
| 52 | + return BinarySearch(mid+1, end, num); |
| 53 | + }else { //arr[mid] > num |
| 54 | + return BinarySearch(start, mid-1, num); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments