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

}
๋ฐฉ๋ฌธํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋Œ“๊ธ€,์ง€์ ,ํ”ผ๋“œ๋ฐฑ ์–ธ์ œ๋‚˜ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค๐Ÿ˜Š

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ