Editorial for Spotting In Sequence II
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Python:
a = int(input())
n = int(input())
nums = list(map(int, input().split()))
found = False
l, r = 0, n - 1
while l <= r:
mid = (l + r) // 2
if a == nums[mid]:
print(mid)
found = True
break
elif a < nums[mid]:
r = mid - 1
else:
l = mid + 1
if found == False:
print(-1)
C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, n;
cin >> a >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) cin >> nums[i];
int l = 0, r = n-1;
while (l < r) {
int mid = (l + r) / 2;
if (a == nums[mid]) {
cout << mid << "\n";
return 0;
} else if (a < nums[mid]) r = mid - 1;
else l = mid + 1;
}
cout << "-1\n";
}
Comments