64分求调

P2249 【深基13.例1】查找

fly_code @ 2024-12-10 17:08:36

#include<bits/stdc++.h>
using namespace std;
int n,m,a[1000020]={0},b[100010]={0};

int search(int s,int l,int r)
{

    while(l<r)
    {
        int mid=(l+r)/2;
        if(a[mid]<s){
            l=mid+1;
        }
        else if(a[mid]>s){
            r=mid;
        }
        else
        {
            while(a[mid-1]==a[mid])
            {
                mid--;
            }
            return mid;
        }
    }
    return -1;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    for(int i=1;i<=m;i++)
    {
        cin>>b[i];
    }
    for(int i=1;i<=m;i++)
    {
        cout<<search(b[i],1,n)<<" ";
    }
    return 0;

 } 

记录这里 必关,谢谢!


by szlyf2011 @ 2024-12-10 17:40:17

@fly_code ,给你参考一下我的思路吧

#include <bits/stdc++.h>
using namespace std;
int a[1000006];
int mm[100005];
int n,m;
int find(int t){
    int l = 0,r = n + 1;
    int mid;
    while(l + 1 < r){
        mid = (l + r) / 2;
        if(a[mid] < t)
            l = mid;
        else
            r = mid;
    }
    if(a[r] == t){
        return r;
    }
    return -1;
}
int main(){ 
    cin >> n >> m;
    for(int i = 1;i <= n;i++){
        cin >> a[i];
    }
    for(int i = 1;i <= m;i++){
        cin >> mm[i];
    }

    for(int i = 1;i <= m;i++){
        cout << find(mm[i]) <<" ";
    }
}

|