Home 10815(숫자 카드)
Post
Cancel

10815(숫자 카드)

첫 시도

  • N,M이 500,000이기 때문에 단순 완탐으로는 시간초과
  • 정렬된 arr를 이분탐색
  • MlogN으로 해결 가능

해결

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;

public class Main {
    static int N;
    static int[] arr1;
    public static void main(String[] ars) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;

        N = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        arr1 = new int[N];
        for (int i = 0; i < N; i++) {
            arr1[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(arr1);

        int M = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < M; i++) {
            int num = Integer.parseInt(st.nextToken());
            sb.append(binarySearch(num)+" ");
        }
        System.out.println(sb);
    }

    public static int binarySearch(int value) {
        int first = 0;
        int last = N - 1;
        int mid = 0;

        while (first <= last) {
            mid = (first + last) / 2;
            if (arr1[mid] == value) {
                return 1;
            }

            if (arr1[mid] < value) {
                first = mid + 1;
            } else {
                last = mid - 1;
            }
        }
        return 0;
    }
}

참고

This post is licensed under CC BY 4.0 by the author.