[PS] 99ν΄λ½ μ½ν μ€ν°λ 13μΌμ°¨ TIL (μ«μμΉ΄λ)
νκ·Έ: 99ν΄λ½, PS, TIL, μ΄λΆνμ, μ½λ©ν μ€νΈμ€λΉ, νν΄99
μΉ΄ν κ³ λ¦¬: PS
λ¬Έμ
νμ΄
binarySearch
μλ° Arrays
ν¨ν€μ§μ μλ binarySearch()
λ©μλλ₯Ό μ΄μ©ν΄ νμλ€. ν΄λΉ λ©μλλ μ λ ¬λ μνμ λ°°μ΄μμ μνλ κ°μ μ°Ύμμ£Όλ μν μ νλ€.
λ΄λΆμ μΌλ‘ μ΄λΆνμμΌλ‘ ꡬνλμ΄ μμ΄ O(log n) μ μκ°λ³΅μ‘λλ₯Ό κ°μ§λ€.
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;
}
}
}
λκΈλ¨κΈ°κΈ°