본문 바로가기

Java/알고리즘

[이분 탐색] 수 찾기

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

 

import java.io.*;
import java.util.*;

public class Main {
    static FastReader scan = new FastReader();

    static int N, L, R;
    static int[] A, B;

    static void input() {
        N = scan.nextInt();
        A = new int[N];
        for (int i = 0; i < N; i++) {
            A[i] = scan.nextInt();
        }
    }

    static int bin_search(int X) {
        // A[L...R] 에서 X가 있으면 true, 없으면 false를 return 하는 함수
        while (L <= R) {
            int mid = (L + R) / 2;
            if (A[mid] == X) {
                return 1;
            } else if (A[mid] > X) {
                R = mid - 1;
            } else if (A[mid] < X) {
                L = mid + 1;
            }
        }
        return 0;
    }

    static void pro() {
        int M = scan.nextInt();
        B = new int[M];
        // 정렬 해주기!
        Arrays.sort(A, 0, N);

        for (int i = 0; i < M; i++) {
            int X = scan.nextInt();
            B[i] = X;
        }
    }

    public static void main(String[] args) {
        input();
        pro();

        for (int i : B) {
            L = 0;
            R = N - 1;
            System.out.println(bin_search(i));
        }
    }


    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;
        }
    }
}

 

  • 주의사항
    • 이분 탐색은 while문이 필수
    • 부등호 잘쓰기
    • 값비교는 항상 mid로 진행
  • 참고사항
    • Math함수
      • Math.abs(a + b)
      • Math.max(a, b)
      • Math.min(a,b)
    • 배열 정렬
      • Arrays.sort(Array변수, 0, 길이)