[백준] 10815 숫자 카드 자바

차누·2023년 8월 24일
0

문제

숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 가지고 있는지 아닌지를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다. 두 숫자 카드에 같은 수가 적혀있는 경우는 없다.
셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다. 넷째 줄에는 상근이가 가지고 있는 숫자 카드인지 아닌지를 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다. 이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다

출력

첫째 줄에 입력으로 주어진 M개의 수에 대해서, 각 수가 적힌 숫자 카드를 상근이가 가지고 있으면 1을, 아니면 0을 공백으로 구분해 출력한다.

풀이방법

이 문제를 풀때 이분탐색을 사용해야한다. 왜냐하면 완전탐색 알고리즘을 사용할시 모든 데이터를 탐색해야 하기때문에 시간도 오래걸리고 코드 제출 시 시간초과가 뜰 수 있기 때문에 이분탐색을 사용하여 풀면 쉽게 풀 수 있다.

주의할점은 이분탐색이 Sort 알고리즘을 사용해 정렬을 해야한다. 왜냐하면 이분탐색 특성상 처음부터 비교를 하지않고 중간값부터 비교하여 큰값, 작은값에 따라 달라지기 때문에 꼭 정렬을 한 상태에서 문제를 풀어야한다.

코드


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class backjoon{
	
	public static void main(String[] args) throws IOException {
		
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		StringTokenizer st;
		
		StringBuilder sb = new StringBuilder();
		
		int num_case = Integer.parseInt(br.readLine());
		
		int [] arr_int = new int[num_case];
		
		 st = new StringTokenizer(br.readLine());
		
		for(int i =0; i < num_case; i++) {
		
			arr_int[i] = Integer.parseInt(st.nextToken());
		}
		
		Arrays.sort(arr_int);
		
		int find_num = Integer.parseInt(br.readLine());
		
		st = new StringTokenizer(br.readLine());
		
		for(int i =0; i < find_num; i++) {
			
			int search_num = Integer.parseInt(st.nextToken());
			
			sb.append(search(arr_int, num_case, search_num) + " ");
		}
		
		 bw.write(sb.toString() + "\n");
	     bw.flush();
	     bw.close();
	     br.close();
	}
	
	static int search(int [] arr, int num_case , int search_num) {
		
		int first_index = 0;
		int mid_index = 0;
		
		int last_index = num_case -1;
		
		while(first_index <= last_index) {
			
			mid_index = (first_index + last_index) / 2;
			
			if(arr[mid_index] == search_num) {
				
				return 1;
			}
			
			//중간값이 찾고자 하는 값보다 작은 경우 밑으론 검사하지 않는다
			if(arr[mid_index] < search_num) {
				
				first_index = mid_index + 1; 
				
			}
			
			else {
				last_index = mid_index -1;
			}
				}
		
		return 0;
	}
	}
profile
to be good programmer

0개의 댓글