#include <iostream>
using namespace std;
long long BinarySearch(long long A[],long long n,long long key)
{
long long i=0,j=n-1;
if(A[0]>key) return 0;
while(i<=j)
{
long long mid=(i+j)/2;
if(key>A[mid])
{
i=mid+1;
}
else if(key<A[mid])
{
j=mid-1;
}
else if(A[mid]==key)
{
return mid+1;
}
}
return i;//没找到返回i
}
int main()
{
long long n,m;
cin>>n>>m;
long long *A=new long long [n];
long long *B=new long long [m];
for(long long i=0;i<n;i++)
{
cin>>A[i];
}
for(long long i=0;i<m;i++)
{
cin>>B[i];
}
for(long long i=0;i<m;i++)
{
long long j=BinarySearch(A,n,B[i]);
cout<<j<<endl;
}
return 0;
}
你这代码……写得也不像向左逼近啊 qwq 如果有多个相等的 A_i,感觉不行吧
参考:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll mn = 1e5 + 10;
ll n, m, a[mn];
signed main()
{
ios::sync_with_stdio(false), cin.tie(0);
cin >> n >> m;
for (ll i = 1; i <= n; ++i)
{
cin >> a[i];
}
while (m--)
{
ll lf = 1, rf = n, k, ans = 0;
cin >> k;
while (lf <= rf)
{
ll cf = (lf + rf) >> 1;
if (a[cf] <= k)
{
ans = cf;
lf = cf + 1;
}
else
{
rf = cf - 1;
}
}
cout << ans << '\n';
}
return 0;
}