caokang @ 2024-01-22 18:43:34
测试样例最后一个询问输出不出来,和示例代码一样,不知道为什么。 代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1000010;
int a[maxn], n, m, q;
int find(int x){
int l = 1, r = n + 1;
while(l < r){
int mid = l + ((r - 1) >> 1);
if(a[mid] >= x) r = mid;
else l = mid + 1;
}
if(a[l] == x) return l;
else return -1;
}
int main(){
scanf("%d %d",&n, &m);
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= m; i++){
cin >> q;
int ans = find(q);
printf("%d ", ans);
}
return 0;
}
输入:
输出: 1 2 最后一个结果一直不输出
by WZWZWZWY @ 2024-01-22 18:48:54
@caokang 你在while中输出mid的值就知道了
by zts201210 @ 2024-01-23 21:08:46
int mid = l + ((r - 1) >> 1);
此代码有问题,括号加错啦!
改一下就应该OK了
AC code:
int mid = (l + r - 1) >> 1;
@caokang
by caokang @ 2024-01-24 15:50:14
@zts201210 谢谢