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