主要使用了 upper_bound
和 lower_bound
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int a[N];
int main() {
int n, q;
scanf("%d%d", &n, &q);
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
while(q--) {
int m;
scanf("%d", &m);
// 使用lower_bound找到m的第一个不小于它的位置
int start = lower_bound(a, a + n, m) - a;
// 使用upper_bound找到m的第一个大于它的位置,然后减1得到m的最后一个位置
int end = upper_bound(a, a + n, m) - a - 1;
// 检查m是否存在于数组中
if (start < n && a[start] == m) printf("%d %d\n", start, end);
else printf("-1 -1\n"); // m不在数组中
}
return 0;
}