Publish:

νƒœκ·Έ: , , , , ,

μΉ΄ν…Œκ³ λ¦¬:

img_3.png

문제

문제 링크

img_3.png

풀이

binarySearch

μžλ°” Arrays νŒ¨ν‚€μ§€μ— μžˆλŠ” binarySearch() λ©”μ†Œλ“œλ₯Ό μ΄μš©ν•΄ ν’€μ—ˆλ‹€. ν•΄λ‹Ή λ©”μ†Œλ“œλŠ” μ •λ ¬λœ μƒνƒœμ˜ λ°°μ—΄μ—μ„œ μ›ν•˜λŠ” 값을 μ°Ύμ•„μ£ΌλŠ” 역할을 ν•œλ‹€. λ‚΄λΆ€μ μœΌλ‘œ μ΄λΆ„νƒμƒ‰μœΌλ‘œ κ΅¬ν˜„λ˜μ–΄ μžˆμ–΄ O(log n) 의 μ‹œκ°„λ³΅μž‘λ„λ₯Ό κ°€μ§„λ‹€.

img_3.png

Arrays.binarySearch() λŠ” 값을 찾으면 ν•΄λ‹Ή 인덱슀λ₯Ό λ°˜ν™˜ν•˜κ³ , κ·Έλ ‡μ§€ μ•ŠμœΌλ©΄ -(insertion point) - 1 의 값을 λ°˜ν™˜ν•œλ‹€. insertion point λž€ λ°°μ—΄μ—μ„œ ν•΄λ‹Ή 값보닀 큰 졜초의 인덱슀λ₯Ό λ§ν•œλ‹€. 예λ₯Όλ“€μ–΄ λ°°μ—΄ [1, 3, 5, 7, 9] μ—μ„œ 6 을 찾으렀고 ν•˜λ©΄ 6보닀 큰 졜초의 μœ„μΉ˜λŠ” 7의 μœ„μΉ˜μΈ 3 이 λœλ‹€. 여기에 -1을 κ³±ν•˜κ³  -1을 ν•œ 값인 -4λ₯Ό λ°˜ν™˜ν•œλ‹€. 즉, μ°ΎμœΌλ €λŠ” 값이 있으면 μ–‘μˆ˜, μ—†μœΌλ©΄ μŒμˆ˜λΌλŠ” 점을 μ΄μš©ν•΄ 문제λ₯Ό ν•΄κ²°ν•œλ‹€.

1
2
3
4
int[] test = {1, 3, 5, 7, 9};
Arrays.sort(test);  // 이뢄탐색은 μ •λ ¬λœ μƒνƒœμ˜ λ°°μ—΄μ—μ„œ λ™μž‘ν•œλ‹€.
int search = Arrays.binarySearch(test, 6);
System.out.println("search = " + search);    // search = -4
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class Main {

  static FastReader scan = new FastReader();
  static StringBuilder sb = new StringBuilder();

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

  static void input() {
    int N = scan.nextInt();
    int[] arr = new int[N];
    for (int i = 0; i < N; i++) {
      arr[i] = scan.nextInt();
    }
    Arrays.sort(arr);
    int M = scan.nextInt();
    for (int i = 0; i < M; i++) {
      int isExist = Arrays.binarySearch(arr, scan.nextInt());
      sb.append(isExist >= 0 ? 1 : 0).append(" ");
    }
    System.out.println(sb);

  }

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

}
λ°©λ¬Έν•΄ μ£Όμ…”μ„œ κ°μ‚¬ν•©λ‹ˆλ‹€! λŒ“κΈ€,지적,ν”Όλ“œλ°± μ–Έμ œλ‚˜ ν™˜μ˜ν•©λ‹ˆλ‹€πŸ˜Š

λŒ“κΈ€λ‚¨κΈ°κΈ°