[백준] 1920 수 찾기

문제보기

이분탐색 구현!

import java.util.*;
import java.io.*;

public class Main{
  static int[] num;
  static int n;

  static int binarySearch(int x){
    int l = 0;
    int r = n-1;
    if( x < num[l] || x > num[r] ){ // 범위 밖의 숫자 예외처리
      return 0;
    }
    int mid = (l+r)/2; 
	
    while( l <= r ){
      mid = (l+r)/2;
      int s = num[mid];
      if(s == x){
        return 1;
      }else if(s < x){
        l = mid+1;
      }else{
        r = mid-1;
      }
    }
    return 0;
  }
  public static void main(String []args) throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    n = Integer.parseInt(br.readLine());
    num = new int[n];
    StringTokenizer st = new StringTokenizer(br.readLine());
    for(int i = 0 ; i < n ; i++){
      num[i] = Integer.parseInt(st.nextToken());
    }
    Arrays.sort(num);

    int m = Integer.parseInt(br.readLine());
    st = new StringTokenizer(br.readLine());

    StringBuilder sb = new StringBuilder();

    for(int i = 0 ; i < m ; i++){
      int t = Integer.parseInt(st.nextToken());
      sb.append(binarySearch(t) + "\n");
    }

    System.out.println(sb);
  }
}

Comments