yeroyore @ 2023-11-07 15:10:05
// 二分查找
int binary_search(int arr[], int a, int b)
{
int start = 0, end = b - 1, mid;
while (start <= end)
{
mid = start + (end - start) / 2;
if (a < arr[mid])
{
end = mid - 1;
}
else if (a > arr[mid])
{
start = mid + 1;
}
else
{
while (1)
{
if (arr[mid] == arr[mid - 1])
{
mid--;
}
else
return mid + 1;
}
return mid + 1;
}
}
return -1;
}
#include <stdio.h>
int main()
{
int n, m;
scanf("%d%d", &n, &m);
int i, arr[n];
// 输入数组
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
// m次询问
int number, no_num[m];
for (int j = 0; j < m; j++)
{
scanf("%d", &number);
no_num[j] = binary_search(arr, number, n);
}
// 打印编号
for (int j = 0; j < m; j++)
{
printf("%d ", no_num[j]);
}
return 0;
}
by zzr1208 @ 2023-11-07 16:01:25
int start = 0, end = b
mid=(start+end)/2;
我目前找到的错 @yeroyore
by Calarence4 @ 2023-11-10 19:44:54
@zzr1208 mid那里楼主写的没错,他那个是防止加法溢出的写法
by Calarence4 @ 2023-11-10 19:46:10
题目要求编号是从1开始的,是不是这个错了