본문 바로가기
알고리즘/Class 2

백준 BOJ 1920번

by edvedv 2022. 8. 18.


 

접근 방법

 

 

순차 탐색으로 풀었더니 시간초과가 떴다. 순차 탐색보다 시간적으로 효율적인 이분 탐색으로 풀면 쉽게 풀 수 있다.

 

이분 탐색은 이전에 올린 글을 참고하자.

https://edvedv.tistory.com/14

 

백준 BOJ 1654번

접근 방법 생각없이 0번부터 탐색하는 burte force 방식으로 구현하면 어김없이 시간초과를 맛 볼 것이다. 이분 탐색으로 풀어야 하는 문제다. 이분 탐색( Binary Search ) 이분 탐색 알고리즘은 정렬되

edvedv.tistory.com

 

 


코드

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int arr[] = new int[in.nextInt()];
        for(int i = 0; i < arr.length; i++){
            arr[i] = in.nextInt();
        }
        int m = in.nextInt();
        Arrays.sort(arr);
        for(int i = 0; i < m; i++){
            int a = in.nextInt();
            if (binarySearch(arr, a) >= 0) {
                System.out.println("1");
            } else {
                System.out.println("0");
            }
        }
    }
    public static int binarySearch(int[] arr, int key){
        int lo = 0;
        int hi = arr.length - 1;
        
        while(lo <= hi){
            int mid = (lo + hi)/2;
            if(key < arr[mid]){
                hi = mid - 1; 
            } else if(key > arr[mid]){
                lo = mid + 1;
            } else
                return mid;
        }
        return -1;
    }
}

'알고리즘 > Class 2' 카테고리의 다른 글

백준 BOJ 1966번  (0) 2022.08.19
백준 BOJ 1929번  (0) 2022.08.18
백준 BOJ 1874번  (0) 2022.08.16
백준 BOJ 1654번  (0) 2022.08.16
백준 BOJ 1436번  (0) 2022.08.15

댓글