#include <stdio.h>
#define N 100010
int n, q;
int array[N]; // N的范围来确定数组开的范围(0,n],开的范围要比n大,10
// 第一次出现位置
int num_1(int q[], int len, int x)
{
int l = -1, r = len;
while (l + 1 < r)
{
int mid = (l + r) / 2;
if (q[mid] < x)
{
l = mid;
}
else
{
r = mid;
}
}
if (q[r] == x)
return r;
else
return -1;
}
// 最后出现位置
int num_2(int q[], int len, int x)
{
int l = -1, r = len;
while (l + 1 < r)
{
int mid = (l + r) / 2;
if (q[mid] <= x)
{
l = mid;
}
else
{
r = mid;
}
}
if (q[l] == x)
return l;
else
return -1;
}
int main()
{
scanf("%d %d", &n, &q);
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
while (q--)
{
int x;
scanf("%d", &x);
int res1 = num_1(array, n, x);
int res2 = num_2(array, n, x);
printf("%d %d\n", res1, res2);
}
return 0;
}
/*输入:
6 3
1 2 2 3 3 4
3
4
5
*/
/*输出:
3 4
5 5
-1 -1
*/
二分查找-B站:五点七边 思路
于 2023-04-02 00:04:26 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)