C++
#include <iostream>
#include <vector>
using namespace std;
void binary_search(vector<int> &nums, int n, int k)
{
int left = 0, right = n-1;
while (left < right) {
int middle = left + ((right - left) >> 1);
if (nums[middle] < k)
left = middle + 1;
else
right = middle;
}
if (left == n || nums[left] != k) {
cout << -1 << " " << -1 << endl;
return;
}
int l = left, r = n;
while (l+1 < r) {
int mid = l + ((r-l) >> 1);
if (nums[mid] <= k)
l = mid;
else
r = mid;
}
cout << left << ' ' << l << endl;
}
int main()
{
int n, q; cin >> n >> q;
vector<int> nums(n);
for (int i = 0; i < n; i ++)
cin >> nums[i];
while (q --) {
int k; cin >> k;
binary_search(nums, n, k);
}
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void binary_search(vector<int> &nums, int n, int k)
{
auto left=lower_bound(nums.begin(), nums.end(), k);
auto right=upper_bound(nums.begin(), nums.end(), k);
if(left == nums.end() || *left!=k) cout << -1 << " " << -1 << endl;
else cout << (int)(left-nums.begin()) << " " << (int)(right-nums.begin()-1) << endl;
}
int main()
{
int n, q; cin >> n >> q;
vector<int> nums(n);
for (int i = 0; i < n; i ++)
cin >> nums[i];
while (q --) {
int k; cin >> k;
binary_search(nums, n, k);
}
return 0;
}
Python
from bisect import *
n, q = map(int, input().split())
lst = list(map(int, input().split()))
for _ in range(q):
k = int(input())
l = bisect_left(lst, k)
r = bisect_right(lst, k)
if l == len(lst) or lst[l] != k:
print("-1 -1")
else:
print(l, r-1)