FengYue_Yu @ 2023-04-03 10:43:38
#include<iostream>
using namespace std;
int a[100005];
int find(int n,int f)
{
int l=1,r=n;
while(l<=r)
{
int mid=l+r>>1;
if(a[mid]>=f)
r=mid;
else
l=mid+1;
}
if(a[l]==f)
return l;
else
return -1;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
for(int i=1;i<=n;i++)
cin>>a[i];
while(m--)
{
int f;
cin>>f;
cout<<find(n,f)<<" ";
}
cout<<endl;
}
}
by FengYue_Yu @ 2023-04-03 10:51:04
之前数组开小了,加大数组后就全都是TLE了
#include<iostream>
using namespace std;
int a[1000005];
int find(int n,int f)
{
int l=1,r=n;
while(l<=r)
{
int mid=l+(r-l)/2;
if(a[mid]>=f)
r=mid;
else
l=mid+1;
}
if(a[l]==f)
return l;
else
return -1;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
for(int i=1;i<=n;i++)
cin>>a[i];
while(m--)
{
int f;
cin>>f;
cout<<find(n,f)<<" ";
}
}
}
by FengYue_Yu @ 2023-04-03 10:52:36
麻了,把边界条件改错了,把
while(l<=r)
改成
while(l<r)
就可以了
by Zpril_20211017 @ 2023-04-03 10:57:56
@FengYue_Yu stl
#include <bits/stdc++.h>
using namespace std;
int a[1000001];
int main()
{
int n,m;
cin >> n >> m;
for(int i = 1;i <= n;i++)
cin >> a[i];
for(int i = 1;i <= m;i++)
{
int c;
cin >> c;
int l = lower_bound(a + 1,a + n + 1,c) - a;
if(a[l] == c)
cout << l << ' ';
else
cout << -1 << ' ';
}
return 0;
}