zht66 @ 2023-10-20 18:07:46
#include<bits/stdc++.h>
using namespace std;
int search(int arr[], int left, int right, int key) {
if (left > right)return -1;
int mid = left + (right - left) / 2;
if (key >arr[mid]) search(arr, mid + 1, right, key);
else if (key <arr[mid]) search(arr, left, mid - 1, key);
else return mid;
}
int main() {
int n, m, arr[1000010];
int q;
int number;
cin >> n >> m;
for (int i = 1; i <= n; i++)cin >> arr[i];
for (int i = 1; i <= m; i++) {
cin >> q;
number = search(arr, 0, n, q);
cout << number << " ";
}
return 0;
}
by Shen_Linwood @ 2023-10-20 18:43:15
我先对拍一下(
顺便,可以看看全局变量,因为把 a[]
设成局部变量然后再传参不仅影响程序的效率而且写起来麻烦
by Shen_Linwood @ 2023-10-20 18:44:38
哦,好像不会影响效率
by Shen_Linwood @ 2023-10-20 18:47:37
不用对拍了,看出来了(
if (key >arr[mid]) search(arr, mid + 1, right, key);
else if (key <arr[mid]) search(arr, left, mid - 1, key);
这里会跳过 mid
我比较懒,就不改了,您自己看看吧
顺便,下面调用的时候您写的是 0,n
by Shen_Linwood @ 2023-10-20 18:49:03
还有,发求助帖建议写点注释,比如这里的 left
和 right
两个端点在不在范围内
by zht66 @ 2023-10-20 19:51:24
@Shen_Linwood 嗯嗯谢谢