[백준/Java] 1920 수 찾기

HEETAE HEO·2022년 3월 11일
0

조건

  1. N 만큼의 배열 사이즈를 받는다.

  2. 배열안에 들어가 정수를 입력받는데 정수의 범위는 -2의 31승 보다 크고 2의 31승보다 작다 (Int의 범위 내)

  3. M 만큼의 개수를 받고

  4. 비교할 정수들을 입력받는다.

예제 입력

해결

이 문제 또한 바로 앞의 듣보잡 문제와 같다 배열에 데이터를 넣어 정렬한 후 이분탐색을 통해 문제를 해결할 것이다.

코드

import java.io.BufferedReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
	
	
	static int N,M;
	static int[] A;
	
	static FastReader scan = new FastReader();
	static StringBuilder sb = new StringBuilder();
	
	static void input() {
		N = scan.nextInt(); // 정수 개수를 입력 받음
		A = new int [N + 1]; // Index를 1부터 시작하기 위해 +1
		for(int i=1;i<=N;i++) {
			A[i] = scan.nextInt(); // 데이터 입력
		}

		
	
	}
	static boolean findAns(int[] A, int L, int R,int x) {
		
		while(L<=R) { // 이분탐색을 실시
			int mid = (L + R) /2 ;
			
			if(A[mid] == x) { // 같은 숫자가 존재하면 true반환
				return true;
			}
			else if(A[mid] < x) { 
				L = mid +1;
			}
			else {
				R = mid - 1;
			}
		}
		
		return false; // 같은 숫자가 존재하지않으면 flase반환
	}
	
	static void find() {
		Arrays.sort(A,1,N+1); //A 배열을 오름차순으로 정렬
		
		M = scan.nextInt(); // 비교할 정수 개수를 입력 받고
		
	for(int i=1 ;i<=M;i++) { // 개수만큼 for문 실행
		int ans = scan.nextInt(); // 정수를 입력받아
		if(findAns(A,1,N,ans)) { // 이분탐색으로 일치하는 숫자있는지 확인
			sb.append(1).append('\n'); // 있다면 1 기록
		}
		else {
			sb.append(0).append('\n'); 없다면 0 기록
		}
	}
	
	System.out.println(sb);	
	}


	public static void main(String[] args) {
		// TODO Auto-generated method stub
	input();
	find();
		
	}
	
	static class FastReader {
	BufferedReader br;
	StringTokenizer st;
	
	public FastReader() {
		br = new BufferedReader(new InputStreamReader(System.in));
		}
	
	public FastReader(String s) throws FileNotFoundException {
		br = new BufferedReader(new FileReader(new File(s)));
		}
	
	
	String next() {
		while(st == null || !st.hasMoreElements()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
		}
	
	int nextInt() {
		return Integer.parseInt(next());
	}
	long nextLong() {
		return Long.parseLong(next());
	}
	
	double nextDouble() {
		return Double.parseDouble(next());
	}
	
	String nextLine() {
		String str= "";
		try {
			str = br.readLine();
		} catch(IOException e) {
			e.printStackTrace();
		}
		return str;
		}
	}

}

profile
Android 개발 잘하고 싶어요!!!

0개의 댓글