본문 바로가기
개발 관련 공부/알고리즘

백준 1920 수찾기

by 슴새 2021. 8. 17.
반응형

import java.util.*;

public class Main {
	public static long arr [];
 
	public static int n;
	public static int m;
	public static void main(String[] args) {
	
		Scanner sc=new Scanner(System.in);
		
		n=sc.nextInt();
		arr=new long [n];
		for(int i=0;i<n;i++) {
			arr[i]=sc.nextInt();
		}
		Arrays.sort(arr);
		
		m=sc.nextInt();
		 
		 for(int i=0;i<m;i++) {
				long start=0;
				long end=n-1;
				long key=sc.nextLong();
				System.out.println(search(start,end,key));		 
		 }
		 
		 
	 
	
	}
	
public static int  search(long start,long end,long key) {
		int mid=(int)((start+end)/2);	
		if(start>end) {
			return 0;
		}
        else if(mid<0||mid>=n) {
			return 0;
		}
		else {
			if(arr[mid]==key)
				return 1;
			else if(arr[mid]>key) {
				return search(start,mid-1,key);
			}
			else {
				return search(mid+1,end,key);
			}
		}
		 
		 
				 
		 
}
	 
        
}

배열을 굳이 2개 두지 않고, 입력을 바로 key값으로 쓰니까 런타임에러가 안났다... 두번째 배열로 풀면 뭔가 인덱스 꼬이는 부분이 있는 듯

첫 이분탐색문제

반응형

'개발 관련 공부 > 알고리즘' 카테고리의 다른 글

백준 9012 괄호  (0) 2021.08.19
백준 10816 숫자카드2  (0) 2021.08.18
백준 2178 미로찾기  (0) 2021.08.16
백준 11724 연결 요소의 개수  (0) 2021.08.13
백준 1012 유기농배추  (0) 2021.08.12

댓글