XuYu0317 @ 2024-01-13 09:32:53
rt, 84pts
#include<bits/stdc++.h>
using namespace std;
const int N = 1000010;
int n, m;
int q[N];
int main(){
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf ("%d", &q[i]);
while(m--) {
int x;
scanf("%d", &x);
int l = 0, r = n;
while (l < r) {
int mid = l + (r - l) / 2;
if (q[mid] >= x) r = mid;
else l = mid + 1;
}
if (q[l] == x) printf("%d ", l);
else printf("-1 ");
}
return 0;
}
by danlao @ 2024-01-13 09:40:52
看不出来问题,你看看我的代码吧
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e6+10;
ll m,n;
ll a[N],x[N],l,s[N];
int find(int d,int n){
ll l=1,r=n,ans=-1;
while(l<=r){
ll mid=(l+r)/2;
if(a[mid]==d){
ans=mid;
r=mid-1;
}
else if(a[mid]<d) l=mid+1;
else if(a[mid]>d) r=mid-1;
}
return ans;
}
int main(){
scanf("%lld%lld",&n,&m);
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
for(int i=1;i<=m;i++){
scanf("%lld",&x[i]);
s[i]=find(x[i],n);
}
for(int i=1;i<=m;i++) printf("%lld ",s[i]);
return 0;
}
by xiaoshumiao @ 2024-01-13 09:50:02
@XuYu0317
int l = 0, r = n;
改成:
int l = 1, r = n;
就行了。
by XuYu0317 @ 2024-01-13 09:50:37
找到错误了 第15行
l = 0
应为
l = 1
by XuYu0317 @ 2024-01-13 09:51:03
@yaodiguoan 感谢您提供参考
by XuYu0317 @ 2024-01-13 09:51:41
此贴结
by XuYu0317 @ 2024-01-13 09:52:30
@xiaoshumiao 感谢您的帮助
by danlao @ 2024-01-13 10:26:34
@XuYu0317 不客气