forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3.cpp
More file actions
39 lines (35 loc) Β· 1.11 KB
/
3.cpp
File metadata and controls
39 lines (35 loc) Β· 1.11 KB
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
#include <bits/stdc++.h>
using namespace std;
// μ΄μ§ νμ μμ€μ½λ ꡬν(λ°λ³΅λ¬Έ)
int binarySearch(vector<int>& arr, int target, int start, int end) {
while (start <= end) {
int mid = (start + end) / 2;
// μ°Ύμ κ²½μ° μ€κ°μ μΈλ±μ€ λ°ν
if (arr[mid] == target) return mid;
// μ€κ°μ μ κ°λ³΄λ€ μ°Ύκ³ μ νλ κ°μ΄ μμ κ²½μ° μΌμͺ½ νμΈ
else if (arr[mid] > target) end = mid - 1;
// μ€κ°μ μ κ°λ³΄λ€ μ°Ύκ³ μ νλ κ°μ΄ ν° κ²½μ° μ€λ₯Έμͺ½ νμΈ
else start = mid + 1;
}
return -1;
}
int n, target;
vector<int> arr;
int main(void) {
// n(μμμ κ°μ)μ target(μ°Ύκ³ μ νλ κ°)μ μ
λ ₯ λ°κΈ°
cin >> n >> target;
// μ 체 μμ μ
λ ₯ λ°κΈ°
for (int i = 0; i < n; i++) {
int x;
cin >> x;
arr.push_back(x);
}
// μ΄μ§ νμ μν κ²°κ³Ό μΆλ ₯
int result = binarySearch(arr, target, 0, n - 1);
if (result == -1) {
cout << "μμκ° μ‘΄μ¬νμ§ μμ΅λλ€." << '\n';
}
else {
cout << result + 1 << '\n';
}
}