https://www.acmicpc.net/problem/1920

 

1920번: 수 찾기

첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들

www.acmicpc.net

코드설명

이분탐색을 반복문으로 구현하여 진행했습니다.

이분탐색을 위하여 A[] 배열을 오름차순 정렬한뒤,

 

M줄의 숫자만큼 이분탐색을 계산합니다.

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;


public class Main {
	
	public static int N;
	public static int[] A;
	public static int M;
	public static int[] B;
    public static void main(String[] args) throws IOException{
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	
    	StringTokenizer st = new StringTokenizer(br.readLine());
    	N = Integer.parseInt(st.nextToken());
    	A = new int[N];
    	st = new StringTokenizer(br.readLine());
    	for(int i=0;i<N;i++) {
    		A[i] = Integer.parseInt(st.nextToken());
    	}
    	//이분탐색을 위한 A[i] 오름차순 정렬
    	Arrays.sort(A);
    	
    	
    	st = new StringTokenizer(br.readLine());
    	M = Integer.parseInt(st.nextToken());
    	st = new StringTokenizer(br.readLine());
    	for(int i=0;i<M;i++) {
    		int answer = 0;
    		int startIdx = 0, endIdx = N - 1;
    		int target = Integer.parseInt(st.nextToken());
    		
    		while(startIdx <= endIdx) {
    			int mid = ( startIdx + endIdx) / 2;
    			if(A[mid] == target) {
    				answer = 1;
    				break;
    			}
    			if(A[mid] < target) startIdx = mid + 1;
    			else if (A[mid] > target) endIdx = mid - 1;
    		}
    		System.out.println(answer);
    	}    	
    }
}

+ Recent posts