给定一个按照升序排列的长度为 n 的整数数组,以及 q 个查询。 对于每个查询,返回一个元素 k 的起始位置和终止位置(位置从 0开始计数)。 如果数组中不存在该元素,则返回 -1 -1。
输入格式
第一行包含整数 n 和 q,表示数组长度和询问个数。 第二行包含 n 个整数(均在 1∼10000 范围内),表示完整数组。 接下来 q
行,每行包含一个整数 k,表示一个询问元素。
输出格式
共 q 行,每行包含两个整数,表示所求元素的起始位置和终止位置。 如果数组中不存在该元素,则返回 -1 -1。
数据范围
1 ≤ n ≤ 100000
1 ≤ q ≤ 10000
1 ≤ k ≤ 10000
输入样例:
6 3
1 2 2 3 3 4
3
4
5
输出样例:
3 4
5 5
-1 -1
lower_bound与upper_bound
lower_bound(first,last,val)
函数返回一个非递减序列[first, last)
中的第一个大于等于值val的地址upper_bound(first,last,val)
函数返回一个非递减序列[first, last)
中的第一个大于值val的地址- 注意左闭右开区间
举例
如图所示:
- lower_bound(0,6,2) -> 1
- lower_bound(0,6,3) -> 3
- lower_bound(0,6,4) -> 5
- upper_bound(0,6,1) -> 1
- upper_bound(0,6,2) -> 3
- upper_bound(0,6,3) -> 5
元素不存在 / 查找失败?
思路:将使用lower_bound()
得到的下标带回数组,若下标在数组中对应的元素不等于目标元素则表示元素不存在
技巧:
a[lower_bound(a,a + n,val) - a] != val
AC代码
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int a[N];
int n,q;
bool check(int u)
{
int l = lower_bound(a,a + n,u) - a;
if (a[l] == u) return true;//元素u存在于数组之中
return false;
}
int main()
{
cin >> n >> q;
for (int i = 0;i < n;i++) scanf("%d",&a[i]);//cin的读入速度慢于scanf
int k;
while (q--)
{
scanf("%d",&k);//查询元素k
if (check(k))
{
int l = lower_bound(a,a + n,k) - a;
int u = upper_bound(a,a + n,k) - a - 1;
printf("%d %d\n",l,u);
}
else printf("-1 -1\n");
}
return 0;
}